Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to get the guard that authenticated the user?

Tags:

laravel

I have a customized LoginController with two functions:

loginCustomer that runs Auth::guard('customer')->attempt(...);

loginEmployee that runs Auth::guard('employee')->attempt(...);

I have customized two guards in config.auth that points to my two Models (Customer and Employee) and protect the routes of backoffice and frontend.

Now in my customized LogoutController i want to run Auth::logout() but it doesn't work because i think it uses the default guard.

It only works if i specify Auth::guard('customer')->logout() or Auth::guard('employee')->logout(), depending the guard that was used to login.

Is there any way to get the guard used to authenticate the user so i can use only Auth::guard($guard)->logout?

like image 382
Ricardo Carvalho Avatar asked Mar 15 '17 12:03

Ricardo Carvalho


People also ask

What is guard in Laravel authentication?

Laravel guards define how users are authenticated for each request. Laravel comes with some guards for authentication, but we can also create ours as well. This will enable us to use Laravel's default authentication system with our Admin and Writer models as well. Open config/auth.

How do I get authenticated users?

The process is fairly simple; users input their credentials on the website's login form. That information is then sent to the authentication server where the information is compared with all the user credentials on file. When a match is found, the system will authenticate users and grant them access to their accounts.


2 Answers

You can use shouldUse method:

After the call of this method you can logout user via guard you was previously set by shouldUse method.

In your case:

if( Auth::guard('customer')->attempt(...) ){
    Auth::shouldUse('customer');
}


if( Auth::guard('employee')->attempt(...) ){
    Auth::shouldUse('employee');
}

After this you can use Auth::logout and previously choosen guard (via shouldUse) will be used:

// just use Auth::logout without Auth::guard(GUARDNAME)->logout()
Auth::logout();

Short documentation about this method: https://laravel.com/api/5.4/Illuminate/Auth/AuthManager.html#method_shouldUse

like image 156
Alexander Reznikov Avatar answered Nov 02 '22 23:11

Alexander Reznikov


This might not be the perfect solution, but it works. Basically, just go through all the guards and check if the user is authenticated by that guard. If he is - log him out. Be aware that this will log him out of all the guards he is logged in to.

This code would go to your logout controller:

  $guards = array_keys(config('auth.guards'));
  foreach ($guards as $guard) {
    if(Auth::guard($guard)->check()) Auth::guard($guard)->logout();
  }
like image 45
Tomasz Rup Avatar answered Nov 02 '22 23:11

Tomasz Rup