Home > Enterprise >  Laravel spatie permissions - how to get an array of super admin users?
Laravel spatie permissions - how to get an array of super admin users?

Time:12-14

Is there a built in method to get an array of ids for all users with Super Admin role? I've searched the docs and not found such a method. I know I can search for users with a permission as follows:

        $invoiceAdmins = User::select('id')
            ->permission( 'manage invoices' )
            ->where( 'is_enabled', 1 )
            ->pluck( 'id' )
            ->toArray();

but not what i need. I also found there is a table of model_has_roles which can be used to get the data like this:

        $roleId = DB::table( 'roles' )
            ->select( 'id' )
            ->where( 'name', 'Super Admin' )
            ->pluck( 'id' )
            ->first();
        $superAdmins = DB::table( 'model_has_roles')
            ->select( 'model_id' )
            ->where( 'model_type', 'App\Models\User' )
            ->where( 'role_id', $roleId )
            ->pluck( 'model_id' )
            ->toArray();

but wondering if there is a way to do this that comes with spatie permissions?

I did try guessing before creating above functionality, this for example fails:

$users = User::role( 'Super Admin' )->pluck( 'id' )->toArray();

I tried a few other things too but nothing worked and it throws an error (like method not found)

Based on the excellence of the spatie permissions product I'd be surprised if it doesn't have a method to return a list of users with a role which would for example be essential if I wished to show my super admins in a list (or users of any other roles)!

Hopefully I can delete this function but this is my final function:

    /**
     * @param string $role
     * @param array $exclude
     * @return array
     */
    private static function getRoleUserIds(string $role = 'Super Admin', array $exclude = [129] ): array
    {
        $roleId = DB::table( 'roles' )
            ->select( 'id' )
            ->where( 'name', $role )
            ->pluck( 'id' )
            ->first();
        $array = DB::table( 'model_has_roles')
            ->select( 'model_id' )
            ->where( 'model_type', 'App\Models\User' )
            ->where( 'role_id', $roleId )
            ->pluck( 'model_id' )
            ->toArray();

        foreach ( $exclude as $id ) {
            unset($array[array_search($id, $array, true)]);
        }

        return $array;
    }

CodePudding user response:

You have to add the Spatie\Permission\Traits\HasRoles trait to your User model. See https://spatie.be/docs/laravel-permission/v5/basic-usage/basic-usage?query=query

In your user model:

use Spatie\Permission\Traits\HasRoles;

class User ...

You can then do

$users = User::role('your_role')->get();

CodePudding user response:

You're just missing the get()

User::role('Super Admin')->get()->pluck('id')->toArray();
  • Related