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

NotAGoodCoder's avatar

Using romanbican's roles package - How do I retrieve all users for a specific role?

I'm just getting started with Eloquent in earnest and have hit a roadblock. How in the world can I retrieve the users for a given role?

Right now I have

$contacts = Role::where('slug', 'contact')->first()->users()->get(); which does retrieve all of the users for the role (Though I'm not sure if this is the best way). The problem is when I try to pass that into the lists() method, I get an ambiguous column because both roles and users have an ID and a name column, and I can't figure out if it's possible to get around this problem without manually populating the array to pass to the view. Here is the code that gives the ambiguous columns error

$contacts = Role::where('slug', 'contact')->first()->users()->lists('name', 'id');

@romanbican Tagging you since it's your package. I'm sure it's possible but I'm banging my head against the wall trying to do this in an eloquent fashion without falling back to a manual join on the tables.

0 likes
3 replies
bobbybouwmann's avatar
Level 88

It's much easier if you use eager loading

$role = Role::with('users')->where('slug', 'contact')->first();
$users = $role->users;

// Now that we know how we can get the users we can do something like this
// This will work, because users is now a collection
$users = $role->users->lists('name', 'id');
1 like
NotAGoodCoder's avatar

See, I had tried this method already, but combining it all into one call and was still getting the ambiguous column error. So just for my own satisfaction, what we're doing is retrieving the role, then retrieving the role's users, which is a collection and the lists() method can then be called on the collection?

Seems like there should be an easier way to do this, but if it works, it works. Thanks for the help :)

ccarver's avatar

Hi @TechDaddies,

Not sure if this helps but I thought I would leave it here incase anyone else needs this answer. This is what I did:

$admins = User::whereHas('roles', function($q){
            $q->where('slug', 'admin');
        })->get();

        foreach ($admins as $admin) {
            var_dump($admin->email);
        }

Please or to participate in this conversation.