How can I specify a guard in middleware for route?

Maihan Nijat picture Maihan Nijat · Mar 28, 2018 · Viewed 12.3k times · Source

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');

Answer

Amit Shah picture Amit Shah · Oct 9, 2018

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.