Skip to content

Instantly share code, notes, and snippets.

@vanderb
Created July 2, 2021 09:50
Show Gist options
  • Save vanderb/bfca0605b02b0502e037ca52ab1c8781 to your computer and use it in GitHub Desktop.
Save vanderb/bfca0605b02b0502e037ca52ab1c8781 to your computer and use it in GitHub Desktop.
Laravel Collection Pagination

// Based on https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb

Setup

  • Create a new Service-Provider app/Providers/CollectionServiceProvider.php
  • Insert code above
  • Register Service-Provider in config/app.php

Usage

You can use that macro like you using pagination-method of model-collection.

$myCollection = $itemCollection->paginate(10);
@foreach($myCollection as $items)
...
@endforeach

{{ $myCollection->links() }}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
class CollectionServiceProvider extends ServiceProvider
{
public function boot()
{
Collection::macro('paginate', function($perPage = 15) {
$page = (Paginator::resolveCurrentPage() ?: 1);
$items = $this instanceof Collection ? $this : Collection::make($this);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, ['path' => Paginator::resolveCurrentPage()]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment