Skip to content

Instantly share code, notes, and snippets.

@brendonexus
Created February 8, 2022 09:21
Show Gist options
  • Save brendonexus/188697acd4997fe0a5cf3622934f4126 to your computer and use it in GitHub Desktop.
Save brendonexus/188697acd4997fe0a5cf3622934f4126 to your computer and use it in GitHub Desktop.
Pagination macro for Collections - Laravel 8
<?php
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
/**
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
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,
]
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment