Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
mom__66 Avatar asked Nov 27 '25 23:11

mom__66


1 Answers

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);
}
like image 177
Milena Schmidt Avatar answered Dec 02 '25 05:12

Milena Schmidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!