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
?
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.
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.
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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With