Search code examples
laravelauthenticationlaravel-authorization

Laravel Policies and Gate ignore if admin is logged


I am using Policies and Gate (Roles - Role_User Users) to assign permissions to users in my Laravel project, everything works fine. But I don't know how the admin account can perform every action without having to assign all the permissions to it.

// AuthServiceProvider
public function boot()
{
    $this->registerPolicies();
    $this->registerStaffPolicies();
    $this->registerTaskPolicies();
    $this->registerDepartmentPolicies();
    $this->registerPositionPolicies();
    $this->registerPermissionPolicies();
}

public function registerStaffPolicies()
{
    Gate::define('staff-view', function($user){
        return $user->hasAccess(['staff-view']);
    });
    Gate::define('staff-add', function($user){
        return $user->hasAccess(['staff-add']);
    });
    Gate::define('staff-edit', function($user){
        return $user->hasAccess(['staff-edit']);
    });
    Gate::define('staff-delete', function($user){
        return $user->hasAccess(['staff-delete']);
    });
}
// registerTaskPolicies ...

// My route
Route::get('/staff', 'StaffController@index')->middleware('can:staff-view');
Route::get('/staff/add', 'StaffController@add')->middleware('can:staff-add');
Route::post('/staff/add', 'StaffController@add')->middleware('can:staff-add');

Solution

  • You could define a gate interceptor for your admin role.

    Gate::before(function ($user, $ability) {
        if ($user->isAdmin()) {
            return true;
        }
    });