5

I use laravel spatie package for user permissions. I need to list all users not belongs to a specific user. For example list all non admin(role) users.

For listing all admin users I used

$users = App\User::role('admin');

I need just opposite to that

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Haris
  • 126
  • 3
  • 11

3 Answers3

6

Try that way:

return $this->users()->whereHas('roles', function ($query) {
    return $query->where('name','!=', 'admin');
})->first();
Adam Kozlowski
  • 5,606
  • 2
  • 32
  • 51
3

You can make 2 querys to get both groups of users that you want. I mean:

1 ) Users who don't have any role.

User::whereDoesntHave('roles')->count()

2 ) Users have any role, but not admin (from Adam Kozlowski answer)

$this->users()->whereHas('roles', function ($query) {
    $query->where('name','!=', 'admin');
})->first();
matthias_h
  • 11,356
  • 9
  • 22
  • 40
1

As its documentation states you can use:

$users = User::role('writer')->get(); // Returns only users with the role 'writer'

The role scope can accept a string, a \Spatie\Permission\Models\Role object or an \Illuminate\Support\Collection object.

Just put the roles you want to query in a collection.