我有一个定制的LoginController有两个函数:
loginCustomer运行Auth :: guard('customer') - > attempt(...);
loginEmployee运行Auth :: guard('employee') - > attempt(...);
我在config.auth中定制了两个警卫,指向我的两个模型(客户和员工)并保护后台和前端的路由.
现在在我的自定义LogoutController中我想运行Auth :: logout()但它不起作用,因为我认为它使用默认的后卫.
它只有在我指定Auth::guard('customer')->logout()或Auth::guard('employee')->logout()取决于用于登录的防护时才有效.
有没有办法让防护用于验证用户,所以我只能使用Auth::guard($guard)->logout?
你可以使用shouldUse方法:
调用此方法后,您可以通过以前通过shouldUse方法设置的防护来注销用户.
在你的情况下:
if( Auth::guard('customer')->attempt(...) ){
Auth::shouldUse('customer');
}
if( Auth::guard('employee')->attempt(...) ){
Auth::shouldUse('employee');
}
Run Code Online (Sandbox Code Playgroud)
在此之后你可以使用Auth :: logout并使用之前选择的guard(via shouldUse):
// just use Auth::logout without Auth::guard(GUARDNAME)->logout()
Auth::logout();
Run Code Online (Sandbox Code Playgroud)
关于此方法的简短文档:https://laravel.com/api/5.4/Illuminate/Auth/AuthManager.html#method_shouldUse
这可能不是完美的解决方案,但它确实有效.基本上,只需检查所有警卫并检查用户是否通过该警卫进行身份验证.如果他是 - 记录他.请注意,这将使他退出他登录的所有警卫.
此代码将转到您的注销控制器:
$guards = array_keys(config('auth.guards'));
foreach ($guards as $guard) {
if(Auth::guard($guard)->check()) Auth::guard($guard)->logout();
}
Run Code Online (Sandbox Code Playgroud)