Search code examples
laravellaravel-middlewarelaravel-route

Route group with multiple middleware checks


In my laravel project i have made my own roles and added them to middleware so i can use auth.admin or auth.superadmin to protect specific routes.

I have a Route::Group for my super admin role, a Route::Group for my admin role and a Route:Group for the standard auth check.

Now i have a specific Route that has to be accessed by the superadmin and the admin. When i place the route in the admin group OR the superadmin group it works. But when i try to place it in both or make a route group where i check for both roles it doesnt. Then i tried making a Route::Group like this:

Route::group(['middleware' => ['auth','auth.admin', 'auth.superadmin']], function() {
        Route::resource('user', 'UserController', ['except' => ['show']]);
});

I was thought this would fix my problem but it didnt.

How can i make a Route Group where only admins and superadmins can acces the route.


Solution

  • Rewrite your middleware to use a setup like this:

    Route::get('/home', ['middleware' => 'roles:admin,superadmin', function () {
       echo '/home';
    }]);
    

    And then using the ... operator you can easily check the parameter $roles as an array:

    // YourMiddleware.php
    public function handle($request, Closure $next, ...$roles)