phplaravellaravel-permission

Laravel Spatie middleware using role OR permission


I am using a Laravel Spatie package, and I have inserted all the permissions that I want and an Admin Role.

What I am trying to do:

I am trying to check in each route whether user is an administrator (can do anything) or not an administrator and has a certain permission.

I have tried to add the | sign.

// Get all seasons
Route::get('/', 'SeasonsController@index')
            -> name('index')
            -> middleware(['role:admin|permission:seasons show active']);

What happened vs. expected behavior:

Whenever I log in with a user that has seasons show active permission I get 403 Forbidden.

But if I removed role:admin, the user got the permission.


Solution

  • It's preferable to work with permissions only.

    Grant all the permission to your role administrator (seasons show active ... and others). Then you will not need role:admin in your middleware.

    To grant all permissions on your role administrator, code like below should do the job:

    $permissions = \Spatie\Permission\Models\Permission::all()
    
    $role = \Spatie\Permission\Models\Role::where('name', 'admin')->first();
    
    // foreach on permissions
       $role->givePermissionTo($permission);
    // end foreach