bitcodr
bitcodr

Reputation: 1454

more than one guard in route

I use laravel framework I want to use more than one guard in my route like :

   Route::group([ 'middleware' => 'jwt.auth', 'guard' => ['biker','customer','operator']], function () {}

I have a script in AuthServiceProvider.php like below in boot section:

  $this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $event) {
        $route = $event->route;
        if (!array_has($route->getAction(), 'guard')) {
            return;
        }
        $routeGuard = array_get($route->getAction(), 'guard');
        $this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) {
            return $this->app['auth']->guard($routeGuard)->user();
        });
        $this->app['auth']->setDefaultDriver($routeGuard);
    });

That work with just one guard in route like 'guard'=>'biker'
So how change that code in AuthServiceProvider.php to work with more than one gaurd in route

Upvotes: 3

Views: 5598

Answers (1)

Marc Bellêtre
Marc Bellêtre

Reputation: 597

I know this is an old question but I just went through this issue and figured out how to solve it by myself. This might be useful for someone else. The solution is very simple, you just have to specify each guard after the name of your middleware separated by commas like this:

Route::group(['middleware' => ['auth:biker,customer,operator'], function() {
    // ...
});

The guards are then sent to \Illuminate\Auth\Middleware\Authenticate function authenticate(array $guards) which checks every guard provided in the array.

This works for Laravel 5.4. Also works for Laravel 6.0.

Upvotes: 15

Related Questions