Skip to content

Instantly share code, notes, and snippets.

@vluzrmos
Created July 20, 2016 14:31
Show Gist options
  • Save vluzrmos/3ce756322702331fdf2bf414fea27bcb to your computer and use it in GitHub Desktop.
Save vluzrmos/3ce756322702331fdf2bf414fea27bcb to your computer and use it in GitHub Desktop.
Laravel Paginate Collection or Array
<?php
/**
* Gera a paginação dos itens de um array ou collection.
*
* @param array|Collection $items
* @param int $perPage
* @param int $page
* @param array $options
*
* @return LengthAwarePaginator
*/
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
@ofumbi
Copy link

ofumbi commented Feb 10, 2024

Collection::macro('paginate', function($perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
if (!isset($options['path'])) {
$options['path'] = '/' . request()->path();
}
return new LengthAwarePaginator(array_values($this->forPage($page, $perPage)->toArray()), $this->count(), $perPage, $page, $options);
});

Failed in L10
Place this in the boot method of your App\Providers\AppServiceProvider;

 Collection::macro('paginate', function ($perPage = 15, $page = null, $options = []) {
    $page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
    return new \Illuminate\Pagination\LengthAwarePaginator(array_values($this->forPage($page, $perPage)->toArray()), $this->count(), $perPage, $page, $options);
});

Use like this

$perPage = 5;
collect([1,2,3,4,5])->paginate($perPage)

@mickela
Copy link

mickela commented Feb 26, 2024

Great, thanks! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment