Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify a guard in middleware for route?

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');
like image 885
Maihan Nijat Avatar asked Mar 28 '18 03:03

Maihan Nijat


People also ask

How do you use middleware on a route?

Assigning Middleware To Routes If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel.

What is Guard () in Laravel?

Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies. Providers define how users are retrieved from your persistent storage.

How do I check my middleware route?

If you put your middleware into the $middleware array of the AppServiceProvider you will have access to the route, as written above. Depending on what you try to achieve, $route->group() with middleware or a service provider might be useful.


1 Answers

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.

like image 185
Amit Shah Avatar answered Oct 25 '22 13:10

Amit Shah