jszobody
jszobody

Reputation: 28901

Laravel 5 pagination issues

I'm running into issues with the rewritten L5 pagination where previous methods are now missing. Specifically lastPage() and total().

  1. Was this an oversight (in which case I'm happy to submit an issue / PR)?

  2. Should I be able to get through to the Collection and calculate it myself? I believe the old paginator allowed something like this with __call(), however Illuminate\Pagination\Paginator.php doesn't appear to even keep a reference to the full Collection around. It immediately slices the $items to match $perPage, leaving me no way to calculate a total or lastPage on my own.

  3. Should I be using LengthAwarePaginator instead? And if so, shouldn't Illuminate\Database\Eloquent\Builder::paginate() return a LengthAwarePaginator instead of Paginator? I'm trying to paginate a DB collection, and getting an instance of Paginator back.

I just want to make sure I understand the thought / direction behind pagination in L5 before I assume there's a bug and submit a GH issue or fix.

Udate: Now that Laravel 5 has been released, this is no longer an issue. I get a LengthAwarePaginator when I paginate() on Builder.

Upvotes: 1

Views: 2128

Answers (2)

Paul
Paul

Reputation: 128

Well, now Laravel support pagination total

You could use like this

$total = $paginatedCollection->total()

Upvotes: 0

muhamin
muhamin

Reputation: 185

i ran in to the same problem. here is what i did extended the eloquent builder class. and since i already have model extended, loaded the new builder from there.

you can load the new builder from the extended model like this

public function newEloquentBuilder($query)
{
   return new \App\ExtendedBuilder($query);
}

bellow i have the extended builder ..................

<?php namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

class ExtendedBuilder extends Builder{

public function lengthawarepaginate($perPage = null, $columns = ['*'])
{
    $page = Paginator::resolveCurrentPage();

    $perPage = $perPage ?: $this->model->getPerPage();

    $this->skip(($page - 1) * $perPage)->take($perPage);

    $queryClone = clone ($this->getQuery());

    $total = $queryClone->skip(0)->take($perPage + 1)->count($columns);


    return new LengthAwarePaginator($this->get($columns)->all(),$total, $perPage, $page, [
        'path' => Paginator::resolveCurrentPath()
    ]);
}

}

this is where i got the original code from

not sure if this is the best way to do it, but it works fine.

Upvotes: 2

Related Questions