Search code examples
phplaravellaravel-permission

Laravel Spatie middleware using role OR permission


I am using 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 admin (can do ANYTHING) or not an admin and has a certain permission.

What I have tried:

I have tried to add | 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 get the permission.


Solution

  • it's preferrable to work with permissions only.

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

    To grant all permissions on your role admin 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