Drupal 10: Load All Users With A Given Role

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:

 

  $userManagerService = \Drupal::service('entity_type.manager')->getStorage('user');
  $users = $userManagerService->loadByProperties(['roles' => $role]);
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
10 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.