Juukie's avatar
Level 22

L5 Custom created simple paginator always returns items for first page.

I would like to create a simple next/prev pagination. So I do this:

$items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$paginator = new \Illuminate\Pagination\Paginator($items, $perPage = 2);

.. but I always get the items for the first page.

JSON output for url with ?page=2:

{"per_page":2,"current_page":2,"next_page_url":"\/?page=3","prev_page_url":"\/?page=1","from":3,"to":4,"data":[1,2]}

In the checkForMorePages method there is a line which seems to be incorrect:

$this->items = $this->items->slice(0, $this->perPage);

Does anybody else have problems with this?

0 likes
5 replies
bestmomo's avatar

When I've had to make a custom pagination I used this service :

<?php namespace App\Services;

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

abstract class Pagination
{

  /**
   * Create paginator
   *
   * @param  Illuminate\Support\Collection  $collection
   * @param  int     $total
   * @param  int     $perPage
   * @param  string  $appends
   * @return string
   */
  public static function makeLengthAware($collection, $total, $perPage, $appends = null)
  {
    $paginator = new LengthAwarePaginator(
      $collection, 
      $total, 
      $perPage, 
      Paginator::resolveCurrentPage(), 
      ['path' => Paginator::resolveCurrentPath()]
    );

    if($appends) $paginator->appends($appends);

    return $paginator->render();
  }
  
}
Juukie's avatar
Level 22

@bestmomo I don't want it to be a LengthAware paginator, just a simple next/prev pagination.

pmall's avatar

@bestmomo why are you doing all this although you can just extends the base paginator to create your own and use it ?

bestmomo's avatar

@pmall you're right, I was using it when L5 was in pre-release, but now we can extend the paginator.

Naim's avatar

Hi,

I faced the same issue today with my manual paginator. So here is the way I tackle it:

As suggested by @pmall and @bestmomo, I created a service that extends the Paginator base class.

Here is the content of that class :

<?php namespace App\Services\Pagination;

use Illuminate\Pagination\Paginator;

class Pagination extends Paginator {

     /**
     * Override parent's class CheckForMorePages method. 
     * For some reason slice starts at index 0 on parent, 
     * so the paginator always returns starting items. 
     *
     * @return void
     */
    protected function checkForMorePages()
    {
        $this->hasMore = count($this->items) > ($this->perPage * $this->currentPage());
        $this->items = $this->items->slice($this->firstItem() -1, $this->perPage);
    }

}

@Juukie : Thanks for pointing out the method that needed to be overrode.

Hope it helps someone else !

Please or to participate in this conversation.