0
votes

I'm using Laravel 5.2 and LengthAwarePaginator to paginate my Collection, everything goes well except the lastPage() method, it gives me 1 as always.

Here is my code:

I build the collection by using foreach loop:

$collection = collect();    
foreach ($rows as $row) {
    $collection->push($row);
}

then I paginate it using:

$collection = $collection->sortBy('id')->forPage($page, $page_limit);
$collection = new LengthAwarePaginator($collection, $collection->count(), $page_limit, $page);
return $collection;

Here is my pagination information:

  1. ->currentPage(): 3 (I am on page 3 right now)
  2. $per_page_limit: 8
  3. Total item in Collection: 77
  4. ->lastPage(): 1 (this is the problem)

My question is why ->lastPage() value is always 1 ?

Any help will be very helpful for me.

Thanks in advance

1

1 Answers

2
votes

It is because your $collection after first line, will only contain 8 items and you are then passing the count of it as second argument to the LengthAwarePaginator - which will return the count of 8 items.

What I would do in your case is the following:

$all = $collection->sortBy('id');
$chunk = $collection->forPage(3, 8);

$paginator = new LengthAwarePaginator($chunk, $all->count(), 8, 3);