Cursor Pagination &amp; Lazy Collections at Scale in Laravel | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Cursor Pagination, Chunked Iteration, and Lazy Collections at Scale in Laravel

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

 Offset pagination breaks under large datasets. Learn how cursor pagination, chunked iteration, and lazy collections each solve different scale problems in Laravel Eloquent — with real query trade-offs explained.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 12 Jul 2026 · Updated 12 Jul 2026 · 4 min read

ShareCopy linkCopied

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

  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)

 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.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [eloquent](https://www.msaied.com/public/articles?search=eloquent)
- [performance](https://www.msaied.com/public/articles?search=performance)
- [pagination](https://www.msaied.com/public/articles?search=pagination)
- [php](https://www.msaied.com/public/articles?search=php)

 Frequently asked questions 
---------------------------

  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.

   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.

   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.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

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

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleJob Batching, Chaining, and Rate-Limited Middleware for Laravel Queues](https://www.msaied.com/public/articles/job-batching-chaining-and-rate-limited-middleware-for-laravel-queues) [Next articleLaravel Broadcasting with Reverb: Private Channels, Presence, and Auth Guards](https://www.msaied.com/public/articles/laravel-broadcasting-with-reverb-private-channels-presence-and-auth-guards)  

   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)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
