2

I'm trying to figure out if there is a simple way to get all the users that have a role or another role.
On the official documentation of Spatie Laravel Permissions, I couldn't find this.

I'm trying like this but I get all the users.

User::role(['Individual', 'Organisation', 'Venue'])->get();

I'm also trying like this:

User::whereHas("roles", function($q) {
                $q->orWhere(function ($query) {
                    $query->where("name", "Individual")
                        ->where("name", "Venue")
                        ->where("name", "Organisation");
                });
            })->get();

In the Db roles table I have:

enter image description here

Davide Casiraghi
  • 15,591
  • 9
  • 34
  • 56
  • swap the `orWhere` to the inner query (3 times) rather than the outer one – apokryfos Nov 03 '20 at 08:12
  • https://github.com/spatie/laravel-permission/blob/master/src/Models/Role.php#L61 The Role model has a "users" method. Just use `Role::findByName()` and then `$role->users` – stokoe0990 Nov 03 '20 at 09:25
  • I apologize, I found out that the first query I was using works properly, just I was not ordering the data I was getting and I could not see at the end the user that I expect to see. – Davide Casiraghi Nov 03 '20 at 10:14

3 Answers3

5

you can try whereIn() to roles() ref link https://laravel.com/docs/8.x/queries#additional-where-clauses

User::with("roles")->whereHas("roles", function($q) {
    $q->whereIn("name", ["Individual","Venue",'Organisation']);
})->get();

try id for better search as it is primary key

User::with("roles")->whereHas("roles", function($q) {
    $q->whereIn("id", [6,7,8]);
})->get();

NOTE here name should match exact string of roles name which in your database

Kamlesh Paul
  • 11,778
  • 2
  • 20
  • 33
3

@Apokryfos meant you to change it like this

User::whereHas("roles", function($q) {
                $q->where("name", "Individual")
                    ->orWhere("name", "Venue")
                    ->orWhere("name", "Organisation");
            })->get();

if you instead want the users to have all roles and not one of the roles

User::whereHas("roles", function($q) {
        $q->where("name", "Individual")
    })->whereHas("roles", function($q) {
        $q->where("name", "Venue")
    })->whereHas("roles", function($q) {
        $q->where("name", "Organisation")
    })->get();
N69S
  • 16,110
  • 3
  • 22
  • 36
2

Get all users who have roles assigned

$users_with_roles = User::has('roles')->get();

Get all users who do not have roles assigned

$users_without_any_roles = User::doesntHave('roles')->get();
Timothy
  • 2,004
  • 3
  • 23
  • 29