AlexanderTGreat
AlexanderTGreat

Reputation: 55

Laravel multi auth protecting route multple middleware not working

I have created an extra middleware admin and I want to protect my routes. Adding one single middleware 'auth' or 'auth:admin' is working.

Route::get('/calendar', function () {
    return view('app', ['data' => []);
})->middleware('auth');

But I want that as an admin you can also access the user routes but this is not working. If I try the following, and I log in as an admin I get redirected to the login page all the time.

Route::get('/information', ['middleware' => ['auth', 'auth:admin'], function () {
    return view('app', ['data' => ['auth' => Auth::check()]]);
}]);

But if I change ['auth', 'auth:admin'] to ['auth:admin','auth'] it is working for admin but not for user. So it seems that only the first element of my middleware in array is being recognized. Does anybody have any idea why my multiple middlewares are working seperate but not together? Any help is appreciated

Upvotes: 2

Views: 1421

Answers (2)

santosh
santosh

Reputation: 11

Route::get('/information', ['middleware' => ['auth', 'auth:admin'],function () {
    return view('app', ['data' => ['auth' => Auth::check()]]);
}]);

in this code. ['auth', 'auth:admin'] that's mean you need to login default guard and admin guard. if you need only login admin guard, ['auth:admin']

Upvotes: 1

lagbox
lagbox

Reputation: 50561

If you are trying to allow multiple 'guards' to be checked for a route you can pass multiple guards as parameters to the Authenticate middleware, auth.

auth:web,admin (assuming web is your default guard).

This will try to resolve a user (Authenticatable) from each guard passed in. If any guard returns a user (Authenticatable) you pass through authenticated. If not you are a guest.

If you set the middleware auth and auth:admin those are 2 separate 'middleware' in the stack that are unrelated.

Upvotes: 5

Related Questions