Get users by role

Hi,

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

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

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

$site->users('organiser')

But it doesn’t work …
Thx

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

Cool, it works :slight_smile:
Thank you!

I’ve tried :

$site->users()->findBy('organizer');

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: