Cursor Pagination &amp; Lazy Collections at Scale in Laravel | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Cursor Pagination, Chunked Iteration, and Lazy Collections at Scale in Laravel        On this page       1. [  Why Offset Pagination Fails at Scale ](#why-offset-pagination-fails-at-scale)
2. [  Cursor Pagination for User-Facing APIs ](#cursor-pagination-for-user-facing-apis)
3. [  Multi-column ordering ](#multi-column-ordering)
4. [  What cursor pagination cannot do ](#what-cursor-pagination-cannot-do)
5. [  Chunked Iteration for Background Processing ](#chunked-iteration-for-background-processing)
6. [  Lazy Collections for Memory-Efficient Streaming ](#lazy-collections-for-memory-efficient-streaming)
7. [  Combining lazy collections with chunking ](#combining-lazy-collections-with-chunking)
8. [  Choosing the Right Tool ](#choosing-the-right-tool)
9. [  Key Takeaways ](#key-takeaways)

  ![Cursor Pagination, Chunked Iteration, and Lazy Collections at Scale in Laravel](https://cdn.msaied.com/415/eb2d62822119280148e092d25b36c6ae.png)

  #laravel   #eloquent   #performance   #pagination   #php  

 Cursor Pagination, Chunked Iteration, and Lazy Collections at Scale in Laravel 
================================================================================

     12 Jul 2026      4 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

  9 sections  

1. [  01   Why Offset Pagination Fails at Scale  ](#why-offset-pagination-fails-at-scale)
2. [  02   Cursor Pagination for User-Facing APIs  ](#cursor-pagination-for-user-facing-apis)
3. [  03   Multi-column ordering  ](#multi-column-ordering)
4. [  04   What cursor pagination cannot do  ](#what-cursor-pagination-cannot-do)
5. [  05   Chunked Iteration for Background Processing  ](#chunked-iteration-for-background-processing)
6. [  06   Lazy Collections for Memory-Efficient Streaming  ](#lazy-collections-for-memory-efficient-streaming)
7. [  07   Combining lazy collections with chunking  ](#combining-lazy-collections-with-chunking)
8. [  08   Choosing the Right Tool  ](#choosing-the-right-tool)
9. [  09   Key Takeaways  ](#key-takeaways)

       Why Offset Pagination Fails at Scale
------------------------------------

Offset-based pagination (`LIMIT 100 OFFSET 50000`) forces the database to scan and discard 50,000 rows before returning your page. On a table with millions of rows and no covering index, this becomes a full or near-full index scan on every page load. The deeper the page, the slower the query — linearly.

Laravel gives you three tools to escape this trap: **cursor pagination**, **chunked iteration**, and **lazy collections**. They solve different problems and are not interchangeable.

---

Cursor Pagination for User-Facing APIs
--------------------------------------

Cursor pagination encodes the last-seen row's ordered column value into an opaque token. The next query uses a `WHERE` clause instead of `OFFSET`:

```php
// Route handler
$orders = Order::orderBy('id')->cursorPaginate(50);

return OrderResource::collection($orders);

```

The generated SQL looks like:

```sql
SELECT * FROM orders WHERE id > 1482930 ORDER BY id ASC LIMIT 50;

```

With an index on `id` (always true for PKs), this is an O(log n) seek regardless of depth. The cursor itself is a base64-encoded JSON payload containing the column values — it is not a page number.

### Multi-column ordering

Cursor pagination works with compound order keys, but every column in `orderBy` must be included in the cursor:

```php
$orders = Order::orderBy('created_at')->orderBy('id')->cursorPaginate(50);

```

Laravel encodes both `created_at` and `id` into the cursor token and generates the correct `WHERE (created_at, id) > (?, ?)` inequality. Ensure a composite index exists:

```php
$table->index(['created_at', 'id']);

```

### What cursor pagination cannot do

- No random page access (you cannot jump to page 47).
- No total count (avoid `withCount` unless you genuinely need it).
- Ordering must be deterministic — avoid nullable columns without a tiebreaker.

---

Chunked Iteration for Background Processing
-------------------------------------------

When you need to process every row in a table — exports, migrations, recalculations — `chunk()` and `chunkById()` are your tools. They are not for pagination; they are for batch processing.

```php
// Dangerous: chunk() with mutations can skip rows
Order::where('status', 'pending')->chunk(500, function ($orders) {
    foreach ($orders as $order) {
        $order->update(['status' => 'processing']); // shifts the result set
    }
});

```

Use `chunkById()` whenever you mutate rows inside the callback. It re-anchors each chunk using the last seen primary key:

```php
Order::where('status', 'pending')
    ->chunkById(500, function ($orders) {
        foreach ($orders as $order) {
            ProcessOrder::dispatch($order);
        }
    });

```

The underlying SQL uses `WHERE id > ? ORDER BY id LIMIT 500` — the same cursor-style seek as cursor pagination, but driven internally.

---

Lazy Collections for Memory-Efficient Streaming
-----------------------------------------------

`LazyCollection` wraps a PHP generator. Eloquent's `cursor()` method streams rows one at a time from the database, keeping only the current model in memory:

```php
Order::where('status', 'pending')
    ->cursor()
    ->each(function (Order $order) {
        ProcessOrder::dispatch($order);
    });

```

This uses a single unbuffered query. Memory stays flat regardless of result set size. The trade-off: the database connection is held open for the entire iteration. For long-running processes or large tables, this can exhaust connection pool slots.

### Combining lazy collections with chunking

```php
Order::cursor()
    ->chunk(200)
    ->each(function ($chunk) {
        Order::whereIn('id', $chunk->pluck('id'))
            ->update(['processed_at' => now()]);
    });

```

This streams rows lazily but batches the writes — a useful hybrid when you need both low memory and efficient bulk updates.

---

Choosing the Right Tool
-----------------------

| Scenario | Tool | |---|---| | User-facing paginated API | `cursorPaginate()` | | Background batch processing | `chunkById()` | | Memory-constrained streaming | `cursor()` + `LazyCollection` | | Bulk mutations on large tables | `chunkById()` | | Piping results through a pipeline | `cursor()` |

---

Key Takeaways
-------------

- Offset pagination degrades linearly; replace it with `cursorPaginate()` for any user-facing list.
- Always prefer `chunkById()` over `chunk()` when mutating rows inside the callback.
- `cursor()` streams one model at a time via a generator — ideal for memory-sensitive pipelines but holds the DB connection open.
- Compound order keys in cursor pagination require matching composite indexes.
- Lazy collections compose with standard Collection methods, making them easy to integrate into existing pipelines.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fcursor-pagination-chunked-iteration-and-lazy-collections-at-scale-in-laravel-2&text=Cursor+Pagination%2C+Chunked+Iteration%2C+and+Lazy+Collections+at+Scale+in+Laravel) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fcursor-pagination-chunked-iteration-and-lazy-collections-at-scale-in-laravel-2) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  Can I use cursor pagination with a non-primary-key sort column?        Yes. Add the column to `orderBy()` and ensure a composite index that includes both the sort column and the primary key as a tiebreaker. Without the tiebreaker, duplicate values in the sort column will cause rows to be skipped or repeated. 

      Q02  When should I use `cursor()` instead of `chunkById()`?        `cursor()` is best when you need to pipe results through a lazy pipeline or keep memory flat without caring about connection duration. `chunkById()` is better for long-running batch jobs where you want to release the connection between chunks and avoid holding it open for minutes. 

      Q03  Does `cursorPaginate()` support total row counts?        No. Cursor pagination intentionally omits the COUNT query for performance. If you need a total, run a separate `count()` query and cache it — but reconsider whether a total is truly necessary for your UI. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Laravel Broadcasting with Reverb: Private Channels, Presence, and Auth Guards](https://cdn.msaied.com/416/26c2793902d9db428140205417b2dfb4.png) laravel reverb broadcasting 

### Laravel Broadcasting with Reverb: Private Channels, Presence, and Auth Guards

Go beyond the basics of Laravel Reverb. Learn how to secure private and presence channels, wire up custom auth...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 12 Jul 2026     4 min read  

  Read    

 ](https://msaied.com/articles/laravel-broadcasting-with-reverb-private-channels-presence-and-auth-guards) [ ![Job Batching, Chaining, and Rate-Limited Middleware for Laravel Queues](https://cdn.msaied.com/414/154bd945ee1677f140cd1ea4132e5b66.png) laravel queues jobs 

### Job Batching, Chaining, and Rate-Limited Middleware for Laravel Queues

Go beyond basic dispatch: learn how to compose Laravel job batches, build reliable chains with catch callbacks...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 12 Jul 2026     3 min read  

  Read    

 ](https://msaied.com/articles/job-batching-chaining-and-rate-limited-middleware-for-laravel-queues) [ ![Laravel Observers vs. Model Events: Choosing the Right Hook for Side Effects](https://cdn.msaied.com/413/ec9d48bb1167db4a2ec2e0784f3be002.png) laravel eloquent observers 

### Laravel Observers vs. Model Events: Choosing the Right Hook for Side Effects

Model events and observers both react to Eloquent lifecycle moments, but picking the wrong one creates hidden...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 11 Jul 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-observers-vs-model-events-choosing-the-right-hook-for-side-effects-1) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
