laravellaravel-authentication

Can I use two guards within one model?


I need to authenticate users in two different ways using one model. Is it possible to define two guards and chose the preferable one e.g. on the controller level?

Also maybe there is a better way to implement that using laravel? Would appreciate any thoughts.


Solution

  • yes it is possible. You should create two different LoginControllers with assigned routes, create two different Auth middleware and probably also change RedirectIfAuthenticated middleware a little bit.

    In both LoginControllers you should define you guard like so:

    protected function guard()
    {
        return Auth::guard('admin');
    }
    

    And if you want to separete routes for your guards than also in RedirectIfAuthenticated Middleware you shold define redirections for both guards

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
    
            if($guard == 'admin') return redirect('/admin');
            return redirect('/');
        }
    
        return $next($request);
    }