Skip to content

Instantly share code, notes, and snippets.

@MehulBawadia
Created March 17, 2018 04:31
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 MehulBawadia/85ad0c50aee97697acd69e3fc76d3ccf to your computer and use it in GitHub Desktop.
Save MehulBawadia/85ad0c50aee97697acd69e3fc76d3ccf to your computer and use it in GitHub Desktop.
Paginate the Laravel Collection
<?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