Created
March 17, 2018 04:31
-
-
Save MehulBawadia/85ad0c50aee97697acd69e3fc76d3ccf to your computer and use it in GitHub Desktop.
Paginate the Laravel Collection
This file contains hidden or 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 | |
namespace App\Utilities\Traits; | |
use Illuminate\Support\Collection; | |
use Illuminate\Pagination\Paginator; | |
use Illuminate\Pagination\LengthAwarePaginator; | |
/* | |
* Paginate the Laravel Collection before and/or after filtering. | |
* | |
* @author MehulBawadia | |
*/ | |
trait PaginateCollection | |
{ | |
/** | |
* Paginate the collection. | |
* | |
* @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Collection $collection | |
* @param integer $perPage | |
* @param integer $currentPage | |
* @return \Illuminate\Pagination\LengthAwarePaginator | |
*/ | |
public function paginate($collection, $perPage = 10, $currentPage = 1) | |
{ | |
$offSet = ($currentPage * $perPage) - $perPage; | |
$otherParams = [ | |
'path' => request()->url(), | |
'query' => request()->query() | |
]; | |
// Visit: https://laracasts.com/discuss/channels/laravel/is-it-paginate-available-collection | |
// View comment of taekunger | |
return new LengthAwarePaginator( | |
$collection->forPage(Paginator::resolveCurrentPage() , $perPage), | |
$collection->count(), | |
$perPage, | |
Paginator::resolveCurrentPage(), | |
$otherParams | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment