How can I paginate a collection?

How can I paginate a collection?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Paginating Merged Collections Without Eloquent Queries

You are running into a common friction point when mixing eager loading patterns with pagination logic in Laravel. The core issue isn't that pagination is impossible for collections; it's that you are attempting to apply database-level constraints after the data has already been fully materialized in memory.

In your current implementation, you fetch all BluePerson records and all RedPerson records using all(), merge them, sort the combined array, and then pass the entire dataset to your view. When you attempt to paginate this $people collection, you are hitting a wall because Laravel's built-in Paginator class is tightly coupled with Eloquent query builders. It expects to handle the LIMIT and OFFSET operations at the database level to ensure that large datasets do not consume excessive server memory or network bandwidth.

Once you have executed ->all() on your models, the ORM has already retrieved every single row from the database and stored it in PHP arrays. The data is now in RAM. If you try to pass this massive array to a standard Paginator, it will simply wrap that entire in-memory dataset and attempt to split it into pages. While this technically works for small datasets, it defeats the primary purpose of pagination: memory efficiency. You are effectively sending gigabytes of data from the database to the application server just to hide 20 items per page from the user.

To paginate a collection that has already been merged and sorted, you must implement a manual paginator. This approach is distinct from the Eloquent Paginate facade because it operates entirely on PHP arrays rather than SQL queries.

Here is how you can construct a custom paginator for your merged collection:

use Illuminate\Pagination\LengthAwarePaginator;

public function index()
{
    $bluePerson = BluePerson::all();
    $redPerson = RedPerson::all();

    // Merge and sort the combined collection
    $people = collect($bluePerson->toArray())
        ->merge($redPerson->toArray())
        ->sortByDesc('created_at');

    // Define pagination settings
    $perPage = 20;
    $page = request('page', 1);
    $totalItems = count($people);
    $totalPages = ceil($totalItems / $perPage);

    // Slice the collection for the current page
    $startItem = ($page - 1) * $perPage;
    $paginatedItems = collect($people)->slice($startItem, $perPage)->values()->all();

    return view('stream.index')
        ->with('people', $paginatedItems)
        ->with('pagination', [
            'currentPage' => $page,
            'lastPage' => $totalPages,
            'firstPage' => 1,
            'perPage' => $perPage,
            'total' => $totalItems,
            'hasMorePages' => $paginatedItems->count() < $people->count(), // Logic to handle edge cases
        ]);
}

In this manual approach, you explicitly calculate the start and end indices using slice(). You then pass the raw slice to your view. Crucially, you must also pass metadata about the pagination state (total items, current page, total pages) to your Blade template so you can render the pagination links correctly.

A significant trade-off with this method is that you lose the ability to use ->where() or other query scopes within the paginator itself. Since the data is already loaded, you cannot filter out "RedPerson" objects on the second page if you didn't do it before merging. You must decide on your filtering logic before the merge operation occurs. If your merged collection grows large, this manual slicing strategy can still lead to memory pressure because the initial ->all() calls load everything at once.

If your goal is strictly to display a unified feed of people regardless of their type, but you want to maintain memory efficiency, consider fetching a limited subset of each model separately and merging those smaller chunks before sorting, or utilizing a database union query that returns only the necessary rows for the first page. However, if performance allows and the dataset fits comfortably in RAM, the manual slice method provides full control over how you present your merged data without relying on Eloquent's specific pagination traits.

Our network