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

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


Something like:

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

will return an array like:

  [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');

To get the current user role in drupal 8 -

$role = \Drupal::currentUser()->getRoles();
foreach ($role as $value) {
   $role = $value;

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.