'How can i paginate laravel collection?
here is how i trying to paginate:
$posts = Post::all()->sortByDesc("created_at")->pagination(1);
but i get this error:
Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
Solution 1:[1]
It is because paginate
is Builder
method, not collection.
You need to create paginator manually, how described here - https://laravel.com/docs/8.x/pagination#manually-creating-a-paginator
Solution 2:[2]
Creating a helper class
<?php
namespace App\Helpers;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class PaginationHelper
{
public static function paginate(Collection $results, $showPerPage)
{
$pageNumber = Paginator::resolveCurrentPage('page');
$totalPageNumber = $results->count();
return self::paginator($results->forPage($pageNumber, $showPerPage), $totalPageNumber, $showPerPage, $pageNumber, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected static function paginator($items, $total, $perPage, $currentPage, $options)
{
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
open the composer.json file after want to add a helpers file, composer has a files key (which is an array of file paths) that you can define inside of autoload
"autoload": {
"files": [
"app/Helpers/PaginationHelper.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
now you have to type this command in the terminal
composer dump-autoload
now you can create a paginate of collections like the example below
Route::get('/test_collect_pagintae', function () {
$users = \App\User::get();
$showPerPage = 20;
$paginated = PaginationHelper::paginate($users, $showPerPage);
return $paginated;
});
Solution 3:[3]
you can use this code in app/provider/serviceProvider in method boot
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
Solution 4:[4]
This is very well solution from simonhamp, thanks simonhamp
My suggestion is execute ->values() in AppServiceProvider like this below. It is important because when slice collection, keys are preserved, we don't want that for paginator.
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$total ? $this : $this->forPage($page, $perPage)->values(),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
Solution 5:[5]
Try this code:
//convert to array
$posts = Post::all()->sortByDesc("created_at")->toArray();
//Create new pagination
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 3;
$currentItems = array_slice($posts, $perPage * ($currentPage - 1), $perPage);
//with path of current page
$posts = (new LengthAwarePaginator($currentItems, count($posts ), $perPage, $currentPage))->setPath(route('posts....'));
//Convert array of array to array of object
$posts->each(function ($item, $itemKey) use($posts) {
$posts[$itemKey] = (Object)$item;
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ehsan Rafiee |
Solution 3 | |
Solution 4 | Adrian |
Solution 5 | Công Th?nh |