Laravel-permission: How to get a list of allUsers->roles?

Created on 15 Mar 2017  路  2Comments  路  Source: spatie/laravel-permission

Hi,
I need to get a list of all my users with the roles of every one (I'm using datatables).
The only way I found is to browse a collection of users then to get role for every one of them.
I think it's the worst way because I'm using N+1 queries if I need to have a list of N users.
I'm sure there's one line of MySql query to write. Can somebody help?

Most helpful comment

One line:

$members = \App\User::with('roles')->get();

Or in a controller method, like:

    public function report_roles()
    {
        // get all roles, for 
        $roles = \Spatie\Permission\Models\Role::all();

        // get all users with all roles
        $members = \App\User::with('roles')->get();

        // filter to list those without the "Member" role
        $nonmembers = $members->reject(function ($user, $key) {
            return $user->hasRole('Member');
        });

        return view('admin.report_roles', ['roles'=>$roles, 'nonmembers' => $nonmembers]);
    }

All 2 comments

One line:

$members = \App\User::with('roles')->get();

Or in a controller method, like:

    public function report_roles()
    {
        // get all roles, for 
        $roles = \Spatie\Permission\Models\Role::all();

        // get all users with all roles
        $members = \App\User::with('roles')->get();

        // filter to list those without the "Member" role
        $nonmembers = $members->reject(function ($user, $key) {
            return $user->hasRole('Member');
        });

        return view('admin.report_roles', ['roles'=>$roles, 'nonmembers' => $nonmembers]);
    }

Thanks a lot, it's a clue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MichalKrakow picture MichalKrakow  路  4Comments

vpratfr picture vpratfr  路  4Comments

devingray picture devingray  路  3Comments

bbdangar picture bbdangar  路  4Comments

ghost picture ghost  路  3Comments