Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Laraveldeep's avatar

Efficient Way To Get List of Users Who Have One or More Roles

Hi,

I have user-role many to many relationship. Also eloquent relationships have been defined on both models.

What is the efficient way to get the list of users who have at least one or more roles (in terms of less steps and non expensive operation)?

Eloquent way to doing thing on this regard is sleek and I like it but couldn't figure out the solution for this.

Yes I can do these:

1. Get pivot table.
2. Get the users.

If I need to get the roles for each user, 
3. Loop through users to get their corresponding roles

But these are multi step process.

Thanks!

0 likes
3 replies
usman's avatar
usman
Best Answer
Level 27

@Laraveldeep to retrieve a users with at least one role you can use the following query on users table:

$users = App\User::has('roles', '>', 0)->with('roles')->get();

This will return a collection of all the users who have at least one role. Since we are eager loading the roles as well, you can access the roles for a perticular user say for the user number one in the collection:

$users[0]->roles->toArray(); 

The above call will retrieve the roles for the first user as an array. Of course this will make sense and has the benefit when you will be looping through the users.

1 like

Please or to participate in this conversation.