2016-12-24 27 views
2

我允許用戶從分頁內容中刪除項目。在刪除用戶請求的項目後,我將它們重定向回來。然而,我注意到這是一個錯誤,因爲如果頁面只包含一個項目並且用戶刪除它,它們將被重定向到現在沒有記錄的同一頁面。我在每個頁面上有11個項目並使用默認的Laravel分頁。如果當前頁面在刪除最後一個或唯一一個項目後是空白的,我該如何執行一個將用戶重定向到上一頁的機制?如果用戶刪除Laravel中當前頁面的最後一項,如何重定向到上一頁?

回答

2

您可以嘗試簡單檢入控制器並手動重定向用戶。代碼只是顯示了這個想法:

$result = Model::paginate(10); 
if (count($result) === 0) { 
    $lastPage = $result->lastPage(); // Get last page with results. 
    $url = route('my-route').'?page='.$lastPage; // Manually build URL. 
    return redirect($url); 
} 

return redirect()->back(); 
+0

看起來問題比我最初看到的要複雜。刪除路線和功能與項目分頁路線和功能不同。這意味着在刪除l重定向回到項目分頁路由之後。這是我在嘗試分頁後計算結果數量的地方。如果結果爲零,那麼我必須再次重定向到頁面參數少於1的項目分頁路由。執行這兩個重定向失敗,結果爲ERR_TOO_MANY_REDIRECTS。思考使用相同的路線刪除和分頁的項目。 –

+0

當您顯示分頁結果並將其傳遞給刪除方法時,您可以創建URI以進行重定向,因爲只有頁面上只有一個結果。或者在有很多結果時發送'null'。然後如果URI是is_null(),則使用此URI或「back()」。 –

1

您可以檢查no。結果,如果小於1,那麼你可以重定向到previousPageUrl爲:

if ($results->count()) { 
    if (! is_null($results->previousPageUrl())) { 
     return redirect()->to($results->previousPageUrl()); 
    } 
} 
0

我解決它通過刪除功能做了Redirect::back()。這導致了paginator功能,其中l做了以下操作:

//if an item was deleted by the user and it was the only on that page the number of 
//items will be zero due the page argument on the url. To solve this we need to 
//redirect to the previous page. This is an internal redirect so we just get the 
//current arguments and reduce the page number by 1. If the page argument is not 
//available it means that we are on the first page. This way we either land on the 
//first page or a previous page that has items 
$input = Input::all(); 
if((count($pages) == 0) && (array_key_exists('page', $input))){ 
    if($input['page'] < 2){ 
     //we are headed for the first page 
     unset($input['page']); 
     return redirect()->action('[email protected]', $input); 
    } 
    else{ 
     //we are headed for the previous page -- recursive 
     $input['page'] -= 1; 
     return redirect()->action('[email protected]', $input); 
    } 
} 
相關問題