Last active
January 31, 2019 15:18
-
-
Save alimranahmed/810836cea1a7b4c44e0d8f2b9c89c095 to your computer and use it in GitHub Desktop.
Extends Laravel collection with paginate() function like Eloquent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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