Spatie Laravel Permissions - How To Get Users that have one Role or another Role

Viewed 6029

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

2 Answers

@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();

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

Related