Eloquent Cursor Pagination &amp; Lazy Collections at Scale | 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 work under the hood in Laravel — and when to reach for each one.

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

ShareCopy linkCopied

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

  On this page +1. [The Problem With Offset at Scale](#the-problem-with-offset-at-scale)
2. [Cursor Pagination](#cursor-pagination)
3. [Gotchas](#gotchas)
4. [Chunked Iteration](#chunked-iteration)
5. [Lazy Collections](#lazy-collections)
6. [Combining Lazy Collections With Chunking](#combining-lazy-collections-with-chunking)
7. [Choosing the Right Tool](#choosing-the-right-tool)
8. [Key Takeaways](#key-takeaways)

 The Problem With Offset 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 a busy write workload, that scan gets expensive fast — and the query plan degrades non-linearly.

Laravel gives you three tools to escape this trap: **cursor pagination**, **chunked iteration**, and **lazy collections**. Each solves a different problem. Reaching for the wrong one wastes either memory or database round-trips.

---

Cursor Pagination
-----------------

Cursor pagination encodes the last-seen row's ordered column value into an opaque token. The next page becomes a `WHERE` clause rather than an `OFFSET`.

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

return UserResource::collection($users);

```

The generated SQL looks like:

```sql
SELECT * FROM users
WHERE id > 3847
ORDER BY id ASC
LIMIT 51; -- one extra to detect next page

```

The cursor itself is a base64-encoded JSON payload containing the column values at the boundary. Laravel's `CursorPaginator` handles encoding and decoding transparently.

### Gotchas

- **You must order by a unique, indexed column** (or a combination that is effectively unique). Non-unique cursors produce inconsistent pages.
- Cursor pagination does not support jumping to arbitrary pages — it is forward/backward only. If your UI needs page numbers, stick with `paginate()`.
- When ordering by a non-unique column (e.g., `created_at`), add `id` as a tiebreaker: `->orderBy('created_at')->orderBy('id')`.

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

```

Laravel will encode both columns into the cursor token automatically.

---

Chunked Iteration
-----------------

When you need to process every row in a table — exports, migrations, backfills — loading everything into memory at once is fatal. `chunk()` issues repeated queries, each fetching a fixed batch.

```php
User::orderBy('id')->chunk(1000, function (Collection $users) {
    foreach ($users as $user) {
        ProcessUser::dispatch($user);
    }
});

```

Under the hood this is still offset-based, so on very large tables the later chunks slow down. Use `chunkById()` instead — it rewrites each batch as a keyed `WHERE id > ?` query:

```php
User::chunkById(1000, function (Collection $users) {
    $users->each(fn ($u) => ProcessUser::dispatch($u));
});

```

`chunkById()` requires an ordered, unique column (defaults to the model's primary key). It is safe to modify rows inside the callback because the cursor advances by ID, not by offset.

---

Lazy Collections
----------------

`LazyCollection` wraps a PHP generator, pulling one row at a time from the database cursor. Memory usage stays flat regardless of result set size.

```php
User::cursor()->each(function (User $user) {
    // Only one User model in memory at a time
    $user->recalculateScore();
    $user->saveQuietly();
});

```

The underlying PDO fetch mode is set to `PDO::FETCH_LAZY`, and Eloquent hydrates one model per iteration. This is ideal for read-heavy pipelines where you do not need to batch database writes.

### Combining Lazy Collections With Chunking

For write-heavy pipelines, combine `cursor()` with `chunk()` on the `LazyCollection` to batch inserts while keeping memory low:

```php
User::cursor()
    ->chunk(500)
    ->each(function (LazyCollection $batch) {
        $records = $batch->map(fn ($u) => [
            'user_id' => $u->id,
            'score'   => $u->computeScore(),
        ])->all();

        Score::upsert($records, ['user_id'], ['score']);
    });

```

This pattern keeps one chunk (500 models) in memory at a time while issuing a single `UPSERT` per batch.

---

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

| Scenario | Tool | |---|---| | API pagination with forward/back navigation | `cursorPaginate()` | | Full-table processing, safe to modify rows | `chunkById()` | | Read-only streaming pipeline, minimal memory | `cursor()` / `LazyCollection` | | Batched writes over a large result set | `cursor()->chunk()` |

---

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

- `OFFSET` pagination degrades at scale; cursor pagination replaces it with an indexed `WHERE` clause.
- Always pair cursor pagination with a unique ordered column or a composite tiebreaker.
- `chunkById()` is safer than `chunk()` when modifying rows inside the callback.
- `LazyCollection::cursor()` holds one model in memory at a time — ideal for streaming reads.
- Combine `cursor()->chunk()` for memory-efficient batched writes over millions of rows.

- [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)
- [database](https://www.msaied.com/public/articles?search=database)
- [pagination](https://www.msaied.com/public/articles?search=pagination)

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

  Can I use cursor pagination with a non-unique sort column like `created\_at`?Yes, but you must add a unique tiebreaker such as `id` to the `orderBy` chain. Laravel will encode both columns into the cursor token, ensuring stable page boundaries even when multiple rows share the same `created\_at` value.

   What is the difference between `chunk()` and `chunkById()` in Eloquent?`chunk()` uses LIMIT/OFFSET internally and can return duplicate or skipped rows if the table is modified during iteration. `chunkById()` advances via a `WHERE id &gt; ?` clause, making it safe to insert, update, or delete rows inside the callback.

   When does `LazyCollection::cursor()` outperform `chunkById()`?`cursor()` is best for read-only streaming pipelines where you process one row at a time and do not need to batch writes. For write-heavy workloads, `chunkById()` or `cursor()-&gt;chunk()` reduces the number of individual database round-trips.

   ![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 in Laravel Queues](https://www.msaied.com/public/articles/job-batching-chaining-and-rate-limited-middleware-in-laravel-queues-2) [Next articlePostgreSQL JSONB in Laravel: Indexing, Querying, and Schema-less Columns Done Right](https://www.msaied.com/public/articles/postgresql-jsonb-in-laravel-indexing-querying-and-schema-less-columns-done-right)  

   On this page
-------------

1. [The Problem With Offset at Scale](#the-problem-with-offset-at-scale)
2. [Cursor Pagination](#cursor-pagination)
3. [Gotchas](#gotchas)
4. [Chunked Iteration](#chunked-iteration)
5. [Lazy Collections](#lazy-collections)
6. [Combining Lazy Collections With Chunking](#combining-lazy-collections-with-chunking)
7. [Choosing the Right Tool](#choosing-the-right-tool)
8. [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)
