AE1995
AE1995

Reputation: 372

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.

Upvotes: 0

Views: 4689

Answers (2)

HabteSoft
HabteSoft

Reputation: 121

you can work with both role and permission by applying on middleware

    //
});

Route::group(['middleware' => ['permission:publish articles|edit articles']], function () {
    //
});

Route::group(['middleware' => ['role_or_permission:super-admin|edit articles']], function () {

You can protect your controllers similarly, by setting desired middleware in the constructor:

{
    $this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}```

Upvotes: 0

Guillaume Cozic
Guillaume Cozic

Reputation: 104

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 

Upvotes: 1

Related Questions