Get users by role


I have different roles in my project. In a template page “organiser”, I want to display the user with the role “organiser”.

I can do it this way:

  • I get all the users
  • I loop on the users collection
  • In the loop, I check if the user has the “organiser” role

See code below

foreach($site->users() as $user): 
    if ($user->hasRole('organiser')):
        <li><?php echo $user->username() ?></li>
<?php endif ?>
<?php endforeach ?>

Anyway, I wonder if I can get the “organiser” directly to avoid looping on all users.
I tried something like this:


But it doesn’t work …

$site->users()->filterBy('role', 'organizer');

Cool, it works :slight_smile:
Thank you!

I’ve tried :


But I was wrong :-/

Yes, findBy() needs a key/value pair as arguments.

I tried with only one “organiser” user and I thought it was ok because $site->users()->findBy(‘role’,‘organiser’); return my only one organiser.

I’ve added two more organiser users and the same line of code $site->users()->findBy(‘role’,‘organiser’); still return only one organiser …

Is there a bug ?

findBy returns the first match. If you want a collection of all matches, use:

$site->users()->filterBy('role', 'organizer');

Sonja posted that originally, but I edited it to findBy because of your original question. :slight_smile:

Ok I get it, thanks for your explanation :slight_smile: