Get all user's roles | Drupal 8

Get all user's roles

Submitted by editor on Wed, 12/09/2015 - 17:00

How to get all user's roles in Drupal 8 ?
How to get a user's roles ?
How to get the current user's roles ?

Get All roles:
    $roles = \Drupal\user\Entity\Role::loadMultiple();

Get a user's roles:
    $uid = 4; //The user ID
    $user = \Drupal\user\Entity\User::load($uid);
    $roles = $user->getRoles();

To get current user's roles :
    $userCurrent = \Drupal::currentUser();
    $user = Drupal\user\Entity\User::load($userCurrent->id());
    $roles = $user->getRoles();


Surf (not verified)

Fri, 03/16/2018 - 13:20

$roleNeeded = 'Staff'

$currentUserId = $currentUserId = \Drupal::currentUser()->id();   \\ or use Drupal\Core\Session\AccountProxyInterface; if using DI

$loadUser = \Drupal::entityTypeManager()->getStorage('user')->load($currentUserId);

$loadUser->set('roles',$roleNeeded );


David Valdez (not verified)

Wed, 04/18/2018 - 05:40

Another way to get all the roles would be using the "user_roles()" function, that function even filter the anonymous users if  we want to.


Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.