1
votes

I have users, roles and role_user table.

User.php

public function roels()
{
    return $this->belongsToMany('Role');
}

Role.php

public function users()
{
    return $this->belongsToMany('User');
}

user could have many roles like admin, sub-admin, member, how to list users by role like all admin or all sub-admin?

1
Just a minor typo, but I think it should be roles() - lozadaOmr

1 Answers

2
votes

There are many ways. Try this:

$admins = User::whereHas('roles', function ($q) {
  $q->where('roles.name', '=', 'admin'); // or whatever constraint you need here
})->get();

or:

$adminRole = Role::where('name', 'admin')->first();
$admins = $adminRole->users;