I need to use paginate and simplepaginate on a collection, so i'm trying to convert the collection into a builder object. To do so I am thinking of creating a function that gets the id of every item in the collection and then builds a query with it, but that seemed to me like a lot of resources waisted, Is there a simpler way ?
-
If you could provide some example that would be awesome... regenerating a collection to a builder is not a good idea... its better to paginate a collection directly when fetching a collection from the database.. laravel.com/docs/8.x/pagination#introductionJenuel Ganawed– Jenuel Ganawed2021-10-19 14:30:40 +00:00Commented Oct 19, 2021 at 14:30
2 Answers
A better way to do this is to build paginator object manually using the existing collection.
From the docs:
Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an
Illuminate\Pagination\PaginatororIlluminate\Pagination\LengthAwarePaginatorinstance, depending on your needs.The
Paginatorclass does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. TheLengthAwarePaginatoraccepts almost the same arguments as thePaginator; however, it does require a count of the total number of items in the result set.In other words, the
Paginatorcorresponds to thesimplePaginatemethod on the query builder and Eloquent, while theLengthAwarePaginatorcorresponds to the paginate method.
Comments
Building on what Alexey said, as alternative, you can build a Paginator from a collection manually. This is a simpler way without the waste of an additional query. e.g.
// Collection $collection
$perPage = 10;
$currentPage = Illuminate\Pagination\Paginator::resolveCurrentPage() ?? 1;
$itemsOnPage = $collection->skip(10 * ($currentPage-1))->take($perPage);
$paginatorPath = Illuminate\Pagination\Paginator::resolveCurrentPath();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$itemsOnPage,
$collection->count(),
$perPage,
$currentPage,
['path' => $paginatorPath]
);
Then in your view,
{!! $paginator->render() !!}