How to check if the current user has a role in Drupal?
\Drupal::currentUser()->hasRole('administrator')
\Drupal::currentUser()->hasRole('administrator')
\Drupal::currentUser()->hasPermission('permission name');
For this we need implement user_login hook and then we check the last access field.
use Drupal\user\Entity\User;
/**
* Implements hook_user_login().
*/
function mymodule_user_login(User $user) {
if (empty($user->getLastAccessedTime())) {
// Do something here.
}
}
Let's imagine we want to send a user to custom route after login in our example to user edit form. How do we do it ?
We need to implement user_login hook
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\user\Entity\User;
/**
* Implements hook_user_login().
*/
function mymodule_user_login(User $user) {
$url = Url::fromRoute('entity.user.edit_form', [
'user' => $user->id(),
]);
$redirect = new RedirectResponse($url->toString());
$redirect->send();
}
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();