Laravel-permission: returning specific role users

Created on 5 Nov 2018  路  6Comments  路  Source: spatie/laravel-permission

I want to return all users with "Admin" role.
How can I get specific role users from controller?

laravel-use support

Most helpful comment

The code I posted above will replace $users with the original values in $users, after removing any that were in $admins.

You can do the same for other roles or reasons. It's just regular Laravel Collections stuff.

All 6 comments

You can use the role scope provided with the package:

$admins = User::role('Admin');

@drbyte hi, thanks for the answer it's working perfectly, as following this question: how can i except this role users from total users? is there a way to do so?

I have

$users = User::withTrashed()->orderby('id', 'desc')->get(); //getting everyone including admins
$admins = User::role('Admin')->get();  //getting admins only

What I want is now that I have admins separately , in $users getting all users except admins.

any idea?

There are a few ways, but perhaps the simplest is to just use Laravel's collection methods to filter out the ones you don't want:

// $users = 
// $admins = 

$users = $users->reject(function($user) use ($admins) {
    return $admins->contains($user);
});

Does this get second value? like we filter admin and editors from users both?

The code I posted above will replace $users with the original values in $users, after removing any that were in $admins.

You can do the same for other roles or reasons. It's just regular Laravel Collections stuff.

This is really working for me thank you for helping me @drbyte

Was this page helpful?
0 / 5 - 0 ratings