2014-10-12 50 views
0

我有一個奇怪的重定向不工作,如果我把重定向的行動外。例如:Laravel返回重定向::不工作以外的行動

下面代碼工作

Route::get('/', '[email protected]'); 

public function index() 
{ 
    if (Auth::check()) 
    { 
     $this->user_id = Auth::id(); 
    } 
    else 
    { 
     return Redirect::to('/'); 
    } 

    // code after check 
} 

但如果我把它拿出來像下面,重定向將不起作用。它根本不重定向。

Route::get('/', '[email protected]'); 

public function index() 
{ 
    $this->authorize();   
    // code after check 
} 

private function authorize() 
{ 
    if (Auth::check()) 
    { 
     $this->user_id = Auth::id(); 
    } 
    else 
    { 
     return Redirect::to('/'); 
    } 
} 

現在,如果我必須在每個動作中繼續使用if語句,那將是麻煩的。相反,我需要調用$ this-> authorize();

任何想法爲什麼它不會工作?

回答

1

您不會返回「返回重定向::」的結果('/');「

試試這個:

public function index() 
{ 
    return $this->authorize();   
} 
+0

嘗試過,但仍然不能正常工作 – jmjap 2014-10-12 06:07:10

+0

Uppss,它實際上是與您的解決方案一起工作。謝謝 – jmjap 2014-10-12 06:15:15

1

只是一個額外的費用。如果我使用我的問題的想法似乎是一個壞方法。 Laravel實際上提供路線保護。所以,現在我用以下步驟更改我的代碼:

in app/filter.php更改重定向到您想要的路線。

Route::filter('auth', function() 
{ 
    if (Auth::guest()) return Redirect::guest('/'); 
}); 

在你的路線保護使用下面的代碼: 路線::得到( '/', '的HomeController @指數');

Route::group(array('before' => 'auth'), function() 
{ 
    // The list of routes you want to protect with authentication 
    Route::get('blabla', '[email protected]'); 
} 

上BlablaController

刪除授權功能在指數函數改變如下:

public function index() 
{ 
    $this->user_id = Auth::id(); 

    // code after check 
} 

現在,它會自動重定向到 '/' 如果沒有通過認證

0

是。身份驗證過濾器是實現身份驗證的最佳方式。

此外,您還可以讓你的routes.php文件更易於閱讀,如果你使用了「路線:在」設置您的過濾器,像這樣:

Route::when('path/*', 'auth'); 

有了這個,你可以儘量少寫入陣列(」在'=>'auth'之前)在你的Route語句中。