Search code examples
laravelroutesmiddlewarelaravel-5.5

how to create middleware that can access by 1 or more role with laravel


I have custom middleware like this

enter image description here

then this is my routes

enter image description here

I want

Route::post('facility', 'FacilityController@store')
        ->name('facility.store')
        ->middleware(['superAdmin', 'admin', 'tenantRelation', 'receptionist']);

can be access by these 4 roles, but always fail.

Anyone can help me? thanks


Solution

  • You are stacking one middleware on top of other, so the request is passed on from one middleware to another and if any failure occur, the request won't be processed further.

    You need to create another middleware that would check whether the user falls under any of the given role.

    php artisan make:middleware RestrictedAccess
    

    and in the handle method of the middleware you could do

    public function handle($request, Closure $next)
    {
        $role_ids = [1, 2, 3, 4];
    
        if (! in_array(auth()->user()->roleId, $role_ids)) {
            abort('403');
        }
    
        return $next($request);
    }
    

    and add the middleware to App\Http\Kernel.php file's

    protected $routeMiddleware = [
        ...
        'auth.restricted_access' => \App\Http\Middleware\RestrictedAccess::class,
        ...
    ];
    

    then you could modify your route as

    Route::post('facility', 'FacilityController@store')
            ->name('facility.store')
            ->middleware('auth.restricted_access');