0

Is there a way to retrieve all users with a specific permission (eg "Post comments"). I only found the possibility to get them by their role:

Drupal::entityQuery('user')
->condition('status', 1)
->condition('roles', 'administrator')
->execute();

or

Drupal::service('entity_type.manager')
->getStorage('user')
->loadByProperties(['roles' => 'administrator']);
1

I had to get the roles that had a given permission to get users with a permission, example:

$roles = user_role_names(FALSE, 'example_permission');
$rids = array_keys($roles);

$uids = Drupal::service('entity_type.manager')->getStorage('user')->getQuery()
  ->condition('roles', $rids, 'IN')
  ->execute();

Apparently thats what Drupal core does in the permission filter for views, see: \Drupal\user\Plugin\views\filter\Permissions

Hope that helps some! Someday it would be nice if core had a way to do an entity query for user_role where you could set a condition for permissions like this:

$rids = Drupal::service('entity_type.manager')->getStorage('user_role')->getQuery()
->condition('permissions', 'example_permission')
->execute();

But I could not get that to work and didn't see any examples in core.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.