2017-04-25 164 views
0

我的大腦突然撞在這一張上。任何關心幫助我的人都非常感激。Laravel 5.4 LengthAwarePaginator

這是LengthAwarepaginator在laravel 5.4

下面是代碼。

$collection = []; 

      foreach ($maincategories->merchantCategory as $merchantCat) { 

       foreach ($merchantCat->merchantSubcategory as $merchantSub) { 

        foreach($merchantSub->products as $products){ 

         $collection[] = $products; 
        } 
       } 
      } 

      $paginate = new LengthAwarePaginator($collection, count($collection), 10, 1, ['path'=>url('api/products')]); 

      dd($paginate); 

它顯示完美,但問題是項目是100.這是我所有的項目,我指定它正確。我只需要顯示10個。

基於LengthAwarePaginator構造函數。這裏是參考。

public function __construct($items, $total, $perPage, $currentPage = null, array $options = []) 

這是屏幕截圖。

enter image description here

我有什麼錯? TY

回答

3

手動創建分頁程序時,必須自行切分結果集。 paginator的第一個參數應該是所需的結果頁面,而不是整個結果集。

pagination documentation

當手動創建一個分頁程序實例,您應該手動「切片」結果的數組傳遞給分頁程序。如果您不確定如何執行此操作,請查看array_slice PHP函數。

我會建議使用集合,以幫助這個一點:

// ... 

$collection = collect($collection); 

$page = 1; 
$perPage = 10; 

$paginate = new LengthAwarePaginator($collection->forPage($page, $perPage), $collection->count(), $perPage, $page, ['path'=>url('api/products')]); 
+0

謝謝...我知道了,這裏是鏈接。 http://psampaz.github.io/custom-data-pagination-with-laravel-5/ – Rbex

+0

@Rbex那篇文章有點老了。我用一些更新的集合代碼(即'forPage()'方法)更新了我的答案。 – patricus

+1

比鏈接更容易。無論如何非常感謝你。你是搖滾明星! – Rbex