Skip to content

Instantly share code, notes, and snippets.

@messi89
Last active March 18, 2020 15:16
Show Gist options
  • Save messi89/31fbe5601c19015770444d2a860e6826 to your computer and use it in GitHub Desktop.
Save messi89/31fbe5601c19015770444d2a860e6826 to your computer and use it in GitHub Desktop.
Laravel paginate collection trait (forPage response formating fixed)
<?php
namespace App\Traits;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
/**
* Collection paginator
*
* @package App\Traits
*/
trait CollectionPaginator
{
protected function collectionPaginate(Collection $results, $total, $pageSize = 10, $pageName= 'name')
{
$page = Paginator::resolveCurrentPage('page');
return self::collectionPaginator(
$results->forPage($page, $pageSize)->values(),
$total,
$pageSize,
$page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
}
/**
* Create a new length-aware paginator instance.
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected function collectionPaginator($items, $total, $perPage, $currentPage, $options)
{
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment