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
Where have I to write this…
Where have I to write this code?
Please follow the Step 1 and…
Please follow the Step 1 and Step 2 of module creation tutorial.
Could you please tell me,…
Could you please tell me, how to get user ID(s) by knowinf his role or name?
Drupal EntityQuery is the…
Drupal EntityQuery is the solution. For that, you can use the following code
$query = \Drupal::entityQuery('user');
$query->condition('name', '%admin%','LIKE');
$ids = $query->execute();
Find Entity using Drupal EntityQuery
Could try this too
$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();
An easier way to get all the roles
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