25

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

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

40

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');
2
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)) {
1
  • 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 '20 at 13:23
1

To get the current user role in drupal 8 -

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

I modified this from another answer for my own use with Drupal 8.

<?php

use Drupal\Core\Session\AccountInterface;

         /**
         * Utility function that checks for single or multiple roles.
         *
         * @param string or array $roles
         *   The role(s) to check.
         *
         * @param AccountInterface $account
         *   The user to check
         *
         * @return bool
         *   Whether the account has the role(s)
         *
         */

        function _user_has_roles($roles, AccountInterface $account) {
            // checks if the account has role(s)
            $roles = is_array($roles) ? $roles : [$roles];
            return !!count(array_intersect($roles, array_values($account->getRoles()));
        };

For example:

$isGeek = _user_has_roles(['maker', 'baker'], \Drupal::currentUser());
$isBaker = _user_has_roles('baker', \Drupal::currentUser());

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.