Use this function to load all users who have a given role.
/**
* Get a list of the user IDs who have a given role.
*
* @param string $role
* The ID of the user role to find.
*
* @return array
* An array of user IDs.
*/
function getUsersByRole(string $role):array {
$query = \Drupal::entityQuery('user');
$query->accessCheck(FALSE);
$query->condition('status', 1)
->condition('roles', $role);
return $query->execute();
}
The "\Drupal::entityQuery('user')" part is a shortcut to the entity type manager service. You can use the entity type manager service to get the entity query in the same way.
$query = \Drupal::entityTypeManager()->getStorage('user')->getQuery();
Note that this query assumes that you do not have lots of users with the given role. Try not to use this code on sites with many thousands of uses with certain roles or might have performance problems.
Comments
Alternatively:
Submitted by Andy on Mon, 10/28/2024 - 21:19
PermalinkAdd new comment