How can I specify a guard in middleware for route?
16,081
Solution 1
If you would like to set a default guard through out the Route::group
then you can use below syntax
Route::group(['middleware' => ['web','auth:visitor_api'], 'prefix' => 'visitor'], function() {
Route::get('/home', 'VisitorController@index')->name('home');
Route::get('/list', 'VisitorController@list')->name('list');
});
after this you can use Auth::id()
instead of Auth::guard('visitor_api')->id()
in your VisitorController.
Solution 2
I think this is what you want
Route::GET('visitors', 'UserController@indexVisitors')->middleware('auth:visitors_api');
You can specify a guard by passing it as a parameter (after the colon character)
You can refer to the laravel documentation:
https://laravel.com/docs/5.6/authentication
Under Authentication Quickstart > Protecting Routes > Specifying A Guard
Author by
Maihan Nijat
Updated on July 19, 2022Comments
-
Maihan Nijat almost 2 years
I have two routes as follow:
Route::GET('admins/', 'UserController@index')->middleware('jwt.auth'); Route::GET('visitors', 'UserController@indexVisitors')->middleware('jwt.auth');
And I have guards in auth.php:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt-auth', 'provider' => 'users', ], 'visitor_api' => [ 'driver' => 'jwt-auth', 'provider' => 'visitors', ], ],
I tried to specify the guard in the middleware but it doesn't work.
Route::GET('visitors', 'UserController@indexVisitors') ->middleware('jwt.auth.visitors_api');
-
Maihan Nijat about 6 yearsThanks for the answer. with the above line it says: guard [visitors_api] not defined and replacing with
jwt.auth:visitors_api
says:User not found' because it tries the defaul guard not the
visitors_api` -
aceraven777 about 6 yearsI don't know anything about
jwt.auth
middleware. Did you installjwt
package? Or did you make your own middleware? -
aceraven777 about 6 yearsCan you provide me the link to the package
-
Maihan Nijat about 6 yearsThe
jwt.auth:visitors_api
is working, but it works also with another user token.