Laravel pattern doesn't work with array instead of collection

I am trying to paginate an array dataset and it turned out to be more complex than I thought.

I am using Laravel 5

So, I have an abstract interface / repository that all my other models propagate to, and I created a method inside my abstract repository. I have included both

use Illuminate\Pagination\Paginator;

and

use Illuminate\Pagination\LengthAwarePaginator;

Here is the method

  public function paginate($items,$perPage,$pageStart=1)
    {

        // Start displaying items from this number;
        $offSet = ($pageStart * $perPage) - $perPage; 

        // Get only the items you need using array_slice
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);

        return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }

      

So, as you can imagine, this function takes an array of variable $items

a $perPage

which indicates how many elements are in the paginate and a $pageStart

indicates which page to start with.

The page works and I see the instance LengthAwarePaginator

, when I do dd()

, all of its values ​​seem to be fine.

The problem starts when I show the results.

When I make the {!! $instances->render() !!}

Bindings paginator appear in order, the parameter page

changes to match the links, but the data doesn't change. The data is the same on every page. When I use Eloquent, for example, Model::paginate(3)

everything works fine, but when I do dd()

this LengthAwarePaginator

, it is identical to LengthAwarePaginator

my custom paginator instance, except that it is partitioning an array, not a collection.

+3


source to share


1 answer


You are not passing the current page as you are, so you will get the same array as well. This will work

public function paginate($items,$perPage)
{
    $pageStart = \Request::get('page', 1);
    // Start displaying items from this number;
    $offSet = ($pageStart * $perPage) - $perPage; 

    // Get only the items you need using array_slice
    $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);

    return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}

      



Your function will also work if you pass the correct value for $pageStart

-Request::get('page', 1)

+11


source







All Articles