A handy package to paginate a collection.
You can install the package via composer:
composer require creativecrafts/laravel-paginate-collection
You can publish the config file with:
php artisan vendor:publish --tag="paginate-collection-config"
This is the contents of the published config file:
return [
/**
* This is the default number of items that will be displayed per page.
* default: 10
*/
'items_per_page' => 10,
/**
* This is the default page name that will be used in the query string.
* default: page
*/
'page_name' => 'page',
];
You can use the Facade to paginate a collection
use CreativeCrafts\Paginate\Facades\Paginate
or use the helper function
use CreativeCrafts\Paginate\Paginate;
$collection = collect([
['name' => 'Jack', 'age' => 40],
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
]);
$paginatedCollection = Paginate::collection($collection, 1);
// output:
// [
// "current_page" => 1
// "data" => [
// 0 => [
// "name" => "Jack"
// "age" => 40
// ]
// ],
// "first_page_url" => "http://localhost:8000/?page=1"
// "from" => 1
// "last_page" => 3
// "last_page_url" => "http://localhost:8000/?page=3"
// "next_page_url" => "http://localhost:8000/?page=2"
// "path" => "http://localhost:8000"
// "per_page" => 1
// "prev_page_url" => null
// "to" => 1
// "total" => 3
// "links" => [
// 0 => [
// "url" => "null",
// "label" => "« Previous",
// "active" => false
// ],
// 1 => [
// "url" => "http://localhost:8000/?page=1",
// "label" => "1",
// "active" => true
// ],
// 2 => [
// "url" => "http://localhost:8000/?page=2",
// "label" => "2",
// "active" => false
// ],
// 3 => [
// "url" => "http://localhost:8000/?page=3",
// "label" => "3",
// "active" => false
// ],
// 4 => [
// "url" => "http://localhost:8000/?page=2",
// "label" => "Next »",
// "active" => false
// ]
// ]
//]
You can get the default items per page from the config file
$paginatedCollection = Paginate::collection($collection, Paginate::defaultItemsPerPage());
You can also get the default page name that will be used in the query string from the config file
$pageName = Paginate::defaultPageName();
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.