5
votes

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?

2

2 Answers

8
votes

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

6
votes

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();
  }