24

How to get the currently logged in user's roles in Drupal 8 ?

For example in D7 we have $GLOBALS['user']->roles;

39

Something like:

$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

will return an array like:

Array
(
  [0] => authenticated
  [1] => administrator
  [2] => some_other_role
)

where the array values are role IDs (equivalent to the machine name of the role in Drupal 7). In OO code, use the appropriate mechanism get the current user from the container, eg

$current_user = $container->get('current_user');
| improve this answer | |
5

This is the way I do it:

// Get actual user role.
$current_user_roles = \Drupal::currentUser()->getRoles();

// Check if user is not admin.
if (!in_array('administrator', $current_user_roles)) {

// Check if user is an admin.
if (in_array('administrator', $current_user_roles)) {
| improve this answer | |
  • 1
    To check if a user is at least one of multiple given roles: if (!empty(array_intersect(['administrator', 'some_other_role'], \Drupal::currentUser()->getRoles()))) { .... – leymannx Aug 19 at 13:23
1

To get the current user role in drupal 8 -

$roles = \Drupal::currentUser()->getRoles();
foreach ($roles as $value) {
   $role = $value;
}
| improve this answer | |
  • 1
    I like your solution, I would just call the variable $roles instead of $role, since getRoles() retrieves all the roles assigned to the user. – Davide Casiraghi Mar 25 at 10:35
  • Thankyou, fixed as suggested ! – Kashmiri Apr 14 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.