Skip to content

Instantly share code, notes, and snippets.

@Rene-Roscher
Created July 13, 2023 22:04
Show Gist options
  • Select an option

  • Save Rene-Roscher/0947079f466df9e73996d7411c0db25f to your computer and use it in GitHub Desktop.

Select an option

Save Rene-Roscher/0947079f466df9e73996d7411c0db25f to your computer and use it in GitHub Desktop.
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\URL;
class CollectionPaginator
{
public function __construct(
protected Collection $collection,
protected $perPage = 15,
protected $currentPage = null
)
{
$this->currentPage = $currentPage ?: Paginator::resolveCurrentPage();
}
public function paginate()
{
$startIndex = ($this->currentPage - 1) * $this->perPage;
$paginatedItems = $this->collection->slice($startIndex, $this->perPage);
return new LengthAwarePaginator(
$paginatedItems,
$this->collection->count(),
$this->perPage,
$this->currentPage,
['path' => URL::current()]
);
}
public static function make(Collection $collection, $perPage = 15, $currentPage = null)
{
return new static($collection, $perPage, $currentPage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment