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

dmcglone's avatar

grabbing only the users with certain roles

I'm having a really hard time getting only users with certain roles. I've tried everything I can think of and I cannot for the life of me understand this.

Get's all the users and their roles with no problem

public function show()
 {
$user = User::with('roles')->get();
           return $user;
}
public function show(User $user)
{

        $user = User::with('roles')->get();
        if($user->hasRole('admin')){
           return $user;
 }
}

The above gives: Call to undefined method Illuminate\Database\Eloquent\Collection::hasRole()

Other than all the above, I've tried many different ways and just can't understand it.

0 likes
10 replies
davorminchorov's avatar

Try something like this:

    $user = User::with('roles');
    $admins = $user->roles()->where('role_name', 'admin')->get();
bestmomo's avatar
$users = User::whereHas('roles', function($q)
{
    $q->where('role', 'admin');
})->get();
1 like
dmcglone's avatar

Thanks guys. @bestmomo that worked. can I ask what made you choose to use a function?

@Ruffles when I tried your solution, I get this error Call to undefined method Illuminate\Database\Query\Builder::roles()

But in my mind it should work, because in my User model I have public function roles() { return $this->belongsToMany('App\Role'); }

I'm interested in knowing why it doesn't work. Hmmmm

dmcglone's avatar

@tuytoosh Some day I will probably use a pre built package, but at the moment I really want to learn from my mistakes by practicing. I believe It's the only way I'm going to learn. :-)

tuytoosh's avatar

@dmcglone , I,m a beginner like you and your idea is entirely correct

(and Laravel is own a pre build package... if you want to "learn" try PHP and OOP and MVC...)

davorminchorov's avatar
$user = User::with('roles')->get(); // maybe it will work if it's a collection? It probably should be an object for it to work.
dmcglone's avatar

Thanks @colourmill, @Ruffles . I'm going to review this stuff today.

@bestmomo I looked at the docs before I posted and couldn't understand what the where was calling for with, 'like' and 'foo%' and got confused, but your example cleared up the confusion :-/

I'm thinking I should ditch the way I'm going about this and base my code on the docs instead of a real world example. That might help me.

Please or to participate in this conversation.