How Laravel 5.4 Uses Guards For Native Multi Authentication

Take a look inside:
/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php

Review the authenticate() method, which takes an array of guards.

protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            return $this->auth->authenticate();
        }
        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }
        throw new AuthenticationException('Unauthenticated.', $guards);
    }

File above is: /vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php

Notice the foreach ($guards as $guard) which means every guard you pass to this must pass the check(), otherwise an AuthenticationException is thrown. TheAuthenticationException can be handled by editing your app/Exceptions/Handler.php file which contains an unauthenticated method.

Thus, you can pass multiple guards to your authentication checks provided you have set-up & defined these guards.

For example, you might have the following 'guards' defined in your config/auth.php file:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'customer' => [
        'driver' => 'session',
        'provider' => 'customer',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

To check against both these guards (to check Auth against multiple guard providers you can do something like this in your Controllers __construct() call (or directly on the method of your choice:

class customerController extends Controller
{

    public function __construct() {
      $this->middleware('auth:customer,web');
    }
... other controller methods...
}

So that would check that the request is coming from a session that has authenticated as both a standard 'web' user and a customer also.

Collect recurring payments with Subscribie - Try Now