2015-10-19 80 views
2

我想將默認的Laravel路線從/auth/login更改爲只有/登錄和與註冊表相對。Laravel 5.1 - 如何在AuthController中設置loginPath?

這是我的路線:

Route::get('login',  ['as' => 'getLogin', 'uses' => 'Auth\[email protected]']); 
Route::post('login', ['as' => 'postLogin', 'uses' => 'Auth\[email protected]']); 
Route::get('logout', ['as' => 'getLogout', 'uses' => 'Auth\[email protected]']); 
Route::get('register', ['as' => 'getRegister', 'uses' => 'Auth\[email protected]']); 
Route::post('register', ['as' => 'postRegister', 'uses' => 'Auth\[email protected]']); 

現在問題出現了,當用戶試圖訪問被把守的區域,在認證類踢,重定向的未認證用戶回/auth/login而不僅僅是/login

不過,我覺得我可以在我的AuthController設置$ LOGINPATH這樣解決問題:

protected $loginPath = '/login'; 

但它似乎像$ LOGINPATH只是用於登錄嘗試失敗,而不是不成功的身份驗證嘗試,如AuthenticateUsers類中所述。

嗯,我設法從這個在身份驗證類改變的redirectUrl:

return redirect()->guest('auth/login'); 

這樣:

return redirect()->guest('login'); 

這解決了問題,但我想設置一個屬性在我的AuthController是這樣的:

protected $redirectIfMiddlewareBlocks = '/login'; 

爲此,我在身份驗證類檢查,如果屬性存在,這是我在AuthController之前設置:

return redirect()->guest(property_exists($this, 'redirectIfMiddlewareBlocks') ? $this->redirectIfMiddlewareBlocks : '/shouldnotbeused'); 

但我得到/shouldnotbeused網址,而不是一個由redirectIfMiddlewareBlocks設置屬性在我的AuthController中。

如何在我的AuthController中正確設置登錄路徑的路徑?

+1

如果存在的話爲什麼要檢查?你知道它存在,因爲你剛剛添加它 – andrewtweber

+1

據我所知,這些是你需要設置登錄路徑的唯一兩個地方。但我不明白爲什麼你要設置屬性並檢查它是否存在,從而使事情變得過於複雜。我只想用'redirect() - > guest('login')'' – andrewtweber

+0

的作品。嗯,我只是有點重構,並認爲這將是一個好主意,將此路徑保存在變量中的某個變量最佳。我檢查它是否存在,看看它是否發現它,它不是 – LoveAndHappiness

回答

2

我認爲問題在於你正在檢查錯誤的類的屬性。要檢查,如果它存在於$this,這是實例身份驗證,當它被設置在AuthController

所以,你應該改變你的檢查:

property_exists(AuthController::class, 'redirectIfMiddlewareBlocks') 

而且,你不能從另一個類訪問受保護的屬性。如果你想這樣做,你必須公開。最後,我會將其設置爲靜態的,以便您不必實例化AuthController對象來訪問它。所以,最終的解決方案是:

class AuthController { 
    public static $redirectIfMiddlewareBlocks = '/here'; 
} 

並在您的身份驗證的中間件:

use App\Http\Controllers\AuthController; 

class Authenticate { 
    public function handle() 
    { 
     return redirect()->guest(property_exists(AuthController::class, 'redirectIfMiddlewareBlocks') ? AuthController::redirectIfMiddlewareBlocks : '/shouldnotbeused'); 
    } 
} 
+0

非常感謝你安德魯。 – LoveAndHappiness

+1

@LoveAndHappiness歡迎您。對不起,我起初誤解了。我所做的**你所做的事情是無稽之談,但實際上你在做什麼,我認爲如你所說,將所有重定向路徑保留在一個地方是一個好主意 – andrewtweber

+0

還有一個問題。與您的解決方案,我得到:使用未定義的常量AuthController - 假設'AuthController' – LoveAndHappiness