2017-03-06 56 views
0

我想爲12條記錄使用paginate方法。我需要12個結果,其中前6個結果出現在第一頁,其餘6個結果出現在第二頁。我曾經在控制器下面的代碼,使用分頁laravel中的有限記錄5.2

$collection = User::take(12)->whereHas('roles', function($q) { 
      $q->where('slug', 'member'); 

     } 
     )->where('status','1')->OrderBy('last_login','desc'); 

我用取(),以獲得12條和使用PAGINATE(6)在一個頁面,因爲這顯示6項結果,

$collection = $collection->paginate(6); 
return View('preferred_matches')->with(array('collection'=>$collection)); 

在我查看,我給這樣的鏈接,

{{ $collection->links() }} 

但是採取(12)不起作用。每頁顯示6個結果,但顯示的結果超過12個。我怎樣才能使用有限的記錄進行分頁。提前致謝。

+0

而不是'take'可以嘗試'限制(12)' –

+0

但仍然沒有效果。我需要的是顯示12條記錄,每頁6個結果。 – Rose

回答

2

Laravel不支持在其默認的分頁限制,但如果限制可以放置在分頁下面的步驟:

首先創建一個模型(假設用戶模型)內的靜態方法

第一步驟:添加這兩個線路的用戶模型

use Illuminate\Pagination\LengthAwarePaginator; 
use Illuminate\Support\Collection; 

第二步的命名空間之後:用戶模型內部只需鍵入以下方法

public static function customPaginate($items,$perPage) 
{ 
    //Get current page form url e.g. &page=6 
    $currentPage = LengthAwarePaginator::resolveCurrentPage(); 

    //Create a new Laravel collection from the array data 
    $collection = new Collection($items); 

    //Define how many items we want to be visible in each page 
    $perPage = $perPage; 

    //Slice the collection to get the items to display in current page 
    $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all(); 

    //Create our paginator and pass it to the view 
    $paginatedSearchResults = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage); 

    return $paginatedSearchResults; 
} 

第三步:在路線或控制器類型的代碼,以查看結果(routes.php假設)

Route::get('/', function(){ 
    $users = DB::table('users')->limit(20)->get(); 
    $paginated_result = App\User::customPaginate($users,3); 
    //dd($paginated_result); 
    return view('show')->with('paginated_result',$paginated_result); 
}); 

希望它將工作。

+0

感謝你的這種方法:) – Rose

0

只是對以前的答案小幅更新,有一個輕微的錯誤,如果集合小於perPage參數,項陣列是空的,這可以通過更換是修復:

$currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();

通過

$currentPageSearchResults = ($items->count() > $perPage) ? $collection->slice($currentPage * $perPage, $perPage)->all() : $collection->all();

在靜態函數

。 感謝@sabuz! ;)

0

只是一個關於以前的答案更多的更新,如果您嘗試訪問「最後一頁」的數據,它也會帶來一個空的結果,解決這個問題,你只需要改變這一行:

$currentPage = LengthAwarePaginator::resolveCurrentPage();

這兩個:

$currentPage = LengthAwarePaginator::resolveCurrentPage(); $currentPage = $currentPage - 1;

我希望它可以幫助別人......