How can I get the roles for the currently logged-in user, in Drupal 8?
In Drupal 7, it could be achieved by accessing $GLOBALS['user']->roles;
.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communitySomething 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');
if (!empty(array_intersect(['administrator', 'some_other_role'], \Drupal::currentUser()->getRoles()))) { ...
.