laravelpermissionsauthorizationlaravel-permission

Laravel Spatie get permissions of admin


In a laravel project using spatie for permissions and roles, I'm facing something pretty strange.

When I call :

$permissions  = $user->getDirectPermissions();
        $roles = $user->getRoleNames();
        return response() ->json([
            'permissions' => $permissions,
            'roles' => $roles
        ]);

If the user is lambda it works fine and retrieve permissions and roles.

If the user is admin, the list of permissions is empty. Why isn't it populated with all of the permissions ?

The goal behind this is to have an API route that retrieve the current logged user for the SPA using this backend.

I could use the admin tag of the roles, but I would prefer to use only pemissions on my frontend.


Solution

  • Likely you have granted your role super admin rights, following the spatie/laravel-permission documentation https://spatie.be/docs/laravel-permission/v5/basic-usage/super-admin

    Gate::before(function ($user, $ability) {
        return $user->hasRole('Super Admin') ? true : null;
    });
    

    Your user does not have any permissions since it has no permissions attached.

    return response() ->json([
        'permissions' => $user->hasRole('Super Admin') ?
            Permission::all() : $permissions,
        'roles' => $roles
    ]);