2013-12-17 26 views
0

也許很簡單,但我完全失去了laravel 4重定向基於控制器關閉的條件

Route::get('/', function() 
{ 
    if(Auth::check()) 
     // send traffic to \Controllers\[email protected] 
    else 
     // send traffic to \Controllers\Loggedout\[email protected] 
}); 

我已經試過:

  • Route::controller
  • URL::action
  • URL::route
  • Redirect::route

我也命名爲兩條路線:

  • Route::get('/', array('as'=>'loggedin', 'uses'=>'Controllers\[email protected]'));
  • Route::get('/', array('as'=>'loggedout', 'uses'=>'Controllers\Loggedout\[email protected]'));

但似乎沒有什麼工作。

我省略了創建控制器的實際代碼,因爲它非常標準,我知道它可以從Route::get('/', 'Controllers\[email protected]')起作用,並且它可以正確返回。


回答

1

我只是寫了一個很好的冗長的答案,這隻意識到我誤解了你的問題。

據我所知,沒有簡單的方法來實現你在單個路由聲明中做什麼,相反,你會想使用兩個。

Route::group(array('before' => 'auth'), function() { 
    Route::get('/', array('as' => '\Controllers\[email protected]')); 
} 

Route::group(array('before' => 'guest'), function() { 
    Route::get('/', array('as' => '\Controllers\Loggedout\[email protected]')); 
} 

在這裏,我們使用過濾器將單個呼叫分組,以便它們不會發生衝突。您不應該在路線中執行任何額外的邏輯,但是如果您絕對必須使用過濾器。

0

,請返回重定向

Route::get('/', function() 
    { 
     if(Auth::check()) 
      return Redirect::route('loggedin'); 
     else 
      return Redirect::route('loggedout'); 
    }); 

其實,這也可能只是最終在重定向循環,你總是返回回/

你想顯示根據不同的頁面關於某些身份驗證狀態?

+0

是啊,我不斷收到重定向循環。用戶被註銷 - >路由到註銷 - >由於某種原因回到這個得到。是的,我想顯示一個登出的屏幕,如果它是'/',而且如果他們登錄,也是主頁。 –

1

這應該可以做到。首先,在你的路線:

// app/routes.php 
Route::get('/', 'Controllers\[email protected]'); 

你的控制器:

// Controllers\Home class 
class Home extends BaseController { 

    public function __construct() 
    { 
     $this->beforeFilter('auth'); 
    } 

    public function index() 
    { 

    } 

} 

最後,您的過濾器:只使用路線

// app/filters.php 
Route::filter('auth', function() 
{ 
    if (! Auth::check()) { 
     return Redirect::action('Controllers\Loggedout\[email protected]'); 
    } 
}); 
+0

當我使用'return Redirect :: action('Controllers \ Loggedout \ Home @ index');',我收到一個錯誤:'Unknown action [Controllers \ Home @ index]'。另外,不要把$ this-> beforeFilter放在控制器中,你也可以做'Route :: get('/',array''''''''auth','uses'=>'Controllers \ Home @ index'));'但是,兩種方法都給我錯誤。 –

+0

檢查你的命名空間是否正確定義,包含在'composer.json'中,並且'composer dump-autoload'。是的,這也可以工作,但假設這是一個「登錄」控制器,您不必在每條路線上以這種方式定義「之前」。 –

0

我的解決方案

Route::get('/', function() 
{ 
    if (Auth::check()) 
     return Redirect::to('dashboard'); 
    else 
     return View::make('index'); 

});