Skip to content

Instantly share code, notes, and snippets.

@sajaddp
Last active November 15, 2022 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sajaddp/870dcd345d1e456349eaf45ca118c890 to your computer and use it in GitHub Desktop.
Save sajaddp/870dcd345d1e456349eaf45ca118c890 to your computer and use it in GitHub Desktop.
Laravel Collection Paginate

In new versions of Laravel, you can create your own paginate. Source: https://laravel.com/docs/9.x/pagination

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

/**
* @param  Collection  $collection
* @param  int  $perPage
* @param  int  $currentPage
* @return LengthAwarePaginator
*/
public static function collectionPaginate(Collection $collection, int $perPage, int $currentPage): LengthAwarePaginator
{
    $perPage = max($perPage, 1);
    $totalPages = ceil($collection->count() / $perPage);
    $currentPage = min($totalPages, max($currentPage, 1));
    $skip = ($currentPage - 1) * $perPage;
    $take = min($collection->count(), $perPage);
    $collection = $collection->skip($skip)
        ->take($take)
        ->values();
    return new LengthAwarePaginator($collection, $totalPages, $perPage);
}

Example:

collectionPaginate(collect([...]), 12, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment