Laravel - How to get a guard who authenticated the user?

I have a custom LoginController with two functions:

loginCustomer, which launches Auth :: guard ('customer') -> attempt (...);

loginEmployee, which starts Auth :: guard ('employee') -> try (...);

I configured two guards in config.auth, which points to my two models (Customer and Employee) and protects the backoffice and frontend routes.

Now in my custom LogoutController I want to run Auth :: logout (), but it does not work, because I think it uses the default protection.

It only works if I specify Auth::guard('customer')->logout()or Auth::guard('employee')->logout(), depending on which protector was used to enter.

Is there a way to get the security used to authenticate the user, so I can only use it Auth::guard($guard)->logout?

+4
source share
2 answers

This may not be the perfect solution, but it works. Basically, just go through all the guards and check if the user is checked by this guard. If he is, get out of him. Keep in mind that this will lead him out of all the guards he entered.

This code will go to your exit controller:

  $guards = array_keys(config('auth.guards'));
  foreach ($guards as $guard) {
    if(Auth::guard($guard)->check()) Auth::guard($guard)->logout();
  }
+4
source

You can use the method shouldUse:

After calling this method, you can log off using the guard function that you previously installed using the method shouldUse.

In your case:

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


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

Auth:: logout ( shouldUse):

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

: https://laravel.com/api/5.4/Illuminate/Auth/AuthManager.html#method_shouldUse

+3

Source: https://habr.com/ru/post/1672349/


All Articles