User access system based on roles and in some cases we want to assign role based on specific business requirements.
For this we need to load a user first:
<?php
use Drupal\user\Entity\User;
// pass the correct user id here.
User:load(4);
or we can load current user
<?php
use Drupal\user\Entity\User;
User::load(\Drupal::currentUser()->id());
Then we add a user role
// pass machine name of the user.
$user->addRole('administrator');
$user->save();
To remove the role we can use this code
// pass machine name of the user.
$user->removeRole('administrator');
$user->save();