2016-12-07 156 views
1

我有一個通過登錄檢查中間件,有多少遊戲有用戶,如果用戶有多個遊戲,我想顯示另一個視圖,但如果用戶有多個遊戲,我每次都會重定向錯誤:Laravel在中間件內部重定向?

這是萬一$assigned_games > 1

$games = Auth::user()->userGames; 
$assigned_games = count($games); 

if ($assigned_games == 1) { 
    return $next($request); 
} elseif ($assigned_games > 1) { 
    return redirect()->route('games.board'); 
} elseif ($assigned_games < 1) { 
    echo "no game bought"; 
    exit; 
} 

我也試過只return route('games.board')但它不工作。

如何在此處設置正確的重定向?

+0

你什麼錯誤? –

+0

@AlexeyMezenin「重新定向了太多次。」 – nowilius

+0

代碼是正確的,但請確保路由games.board不使用此中間件,因爲如果games.board路由使用該中間件它將進入重定向循環,因此您重定向的路由不應再次重定向。 –

回答

2

如果兩個路線是內部的中間件,那麼你應該檢查當前的路線,如果它一樣要重定向你不應該重定向到避免重定向循環

$games = Auth::user()->userGames; 
$assigned_games = count($games); 

if ($assigned_games == 1) { 
    return $next($request); 
} elseif ($assigned_games > 1 && \Route::currentRouteName() != 'games.board') { 
    return redirect()->route('games.board'); 
} elseif ($assigned_games < 1) { 
    echo "no game bought"; 
    exit; 
} else { 
    return $next($request); 
} 
+0

它的工作原理,但現在我總是重定向到這個頁面,可以通過登錄來限制這個請求嗎? – nowilius

+0

在路由中的這個中間件之前添加auth中間件。所以前例。 Route :: group(['middleware'=> ['auth','yourmiddleware']],function(){}); 然後它只會在登錄後纔會進入您的中間件。 –