Get all user's roles | Drupal 8

Get all user's roles

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

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();

Comments

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

$loadUser->save();

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. 

https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_roles/8.6.x

 

Add new comment