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

Share:
16,081
Maihan Nijat
Author by

Maihan Nijat

Updated on July 19, 2022

Comments

  • Maihan Nijat
    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
    Maihan Nijat about 6 years
    Thanks 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
    aceraven777 about 6 years
    I don't know anything about jwt.auth middleware. Did you install jwt package? Or did you make your own middleware?
  • aceraven777
    aceraven777 about 6 years
    Can you provide me the link to the package
  • Maihan Nijat
    Maihan Nijat about 6 years
    The jwt.auth:visitors_api is working, but it works also with another user token.