2017-03-15 23 views
4

我有兩個功能,一個定製的LoginController:Laravel - 如何獲得認證用戶的守衛?

loginCustomer運行驗證::後衛( '客戶') - >嘗試(...);

loginEmployee運行Auth :: guard('employee') - > attempt(...);

我已經在config.auth中定製了兩個指向我的兩個模型(客戶和員工)的保護並保護後臺和前端的路由。

現在在我的自定義LogoutController中,我想運行Auth :: logout(),但它不起作用,因爲我認爲它使用了默認警衛。

它只適用於我指定Auth::guard('customer')->logout()Auth::guard('employee')->logout(),取決於用於登錄的警衛。

有沒有辦法讓後衛用來認證用戶,所以我只能用Auth::guard($guard)->logout

回答

4

這可能不是完美的解決方案,但它的工作原理。基本上,只需通過所有警衛,並檢查用戶是否被該警衛認證。如果他是 - 註銷他。請注意,這會使他退出登錄的所有警衛。

該代碼會去你的註銷控制器:

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

這不是一個完美的解決方案,因爲它不會返回警衛,但它解決了註銷的主要目標 –

3

您可以使用shouldUse方法:

你以前由shouldUse方法設置的這個方法,你可以通過後衛註銷用戶的電話後。

你的情況:

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


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

這一點,你可以使用驗證::註銷和以前choosen後衛(通過shouldUse)後,將用於:

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

簡短的文檔,有關此方法:https://laravel.com/api/5.4/Illuminate/Auth/AuthManager.html#method_shouldUse

+0

我'已經嘗試過您的解決方案,但它在LougoutController中無效。但它在登錄功能中起作用,所以我在嘗試之前添加了Auth :: shouldUse('customer'),並將Auth :: guard('customer') - 嘗試(...)添加到Auth :: atempt(...) –

+0

我做了額外的測試,並意識到您的解決方案通過將註銷功能從LogoutController移動到LoginController來工作。 –

+0

我很高興聽到這個消息。 –