Skip to content

Instantly share code, notes, and snippets.

@alimranahmed
Last active January 31, 2019 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alimranahmed/810836cea1a7b4c44e0d8f2b9c89c095 to your computer and use it in GitHub Desktop.
Save alimranahmed/810836cea1a7b4c44e0d8f2b9c89c095 to your computer and use it in GitHub Desktop.
Extends Laravel collection with paginate() function like Eloquent
<?php
//----------------------------------------How to use?----------------------------------------------
// 1. Add the following private method in App\Providers\AppServiceProvider class
// 2. Call this function from boot() method of same class: $this->extendCollectionWithPaginate();
//-------------------------------------------------------------------------------------------------
/**
* Macro to extends Laravel Collection
* If you have a collection called $item and you want to paginate it like Eloquent paginate:
* $items->paginate($perPage)
*/
private function extendCollectionWithPaginate()
{
if (!\Illuminate\Support\Collection::hasMacro('paginate')) {
\Illuminate\Support\Collection::macro('paginate',
function ($perPage = 15, $page = null, $options = []) {
$options = empty($options) ? ['path' => request()->url()] : $options;
$page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
return (new \Illuminate\Pagination\LengthAwarePaginator(
$this->forPage($page, $perPage),
$this->count(),
$perPage,
$page,
$options
));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment