3

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

bitcodr
  • 1,395
  • 5
  • 21
  • 44
  • I don't think Laravel allows multiple guards on a route. You probably need to rethink your strategy based on this (i.e. single guard and achieve this functionality via middleware) – apokryfos Sep 07 '16 at 12:14
  • because i have 3 guard in my `auth.php` and laravel can't set multi guard to default , and when i run an api with jwt to parse that token to know what user type requested shows me `user_not_found` , because is 3 model for users and i don't know how handle users with multiple model – bitcodr Sep 07 '16 at 12:25
  • The problem is that what you're doing is not a standard thing to do so Laravel can't deal with it out of the box, which is why I suggested you switch to the standard way of doing things, i.e., single user model, single guard and different user type checks via middleware. Otherwise you'd have to basically rewrite your own custom authentication drivers and guards. – apokryfos Sep 07 '16 at 12:29

1 Answers1

15

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.

dbp
  • 19
  • 1
  • 10
Marc Bellêtre
  • 567
  • 5
  • 23