0

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.

Collin
  • 914
  • 1
  • 9
  • 30
  • 1
    Create a new middleware that checks if user has either of roles. – rits Aug 08 '19 at 13:39
  • this should work. what error you are getting?? – zahid hasan emon Aug 08 '19 at 13:40
  • @zahidhasanemon I thought it would work, i dont get any error but i get redirected to /home. Is i place the route in one of the role groups it works but if i combine them they both dont work, i just get redirected. – Collin Aug 08 '19 at 14:02

1 Answers1

1

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)
Flame
  • 6,663
  • 3
  • 33
  • 53
  • I understand that this option might work. I might be stubborn but i would like to know why my solution doesnt work. Just so i can learn from it. – Collin Aug 08 '19 at 14:05
  • well first of all you are duplicating logic in your middleware. They are both checking for a role. Next: middleware is run in series, which means that if `auth.admin` fails (the user is not an admin), then that middleware redirects to a 403 page for instance. You cant and shouldnt do `OR` comparisons between middleware. – Flame Aug 08 '19 at 14:11