The Problem With get() on Large Tables
Calling Model::all() or ->get() on a table with hundreds of thousands of rows loads every hydrated Eloquent model into memory simultaneously. On a 512 MB PHP worker this is a fast path to an OOM kill.
Laravel ships with several mechanisms to avoid this. Picking the wrong one for the job is a common source of subtle bugs and unnecessary database round-trips.
chunk(): Reliable but Stateful
chunk() issues repeated LIMIT / OFFSET queries and hands each page to a closure.
User::orderBy('id')->chunk(500, function (Collection $users) {
foreach ($users as $user) {
ProcessUser::dispatch($user);
}
});
Critical caveat: if you mutate (update or delete) rows inside the closure and those rows affect the ORDER BY column, the offset shifts and you silently skip records. Use chunkById() instead — it re-anchors each page on the last seen primary key:
User::chunkById(500, function (Collection $users) {
$users->each(fn($u) => $u->update(['synced_at' => now()]));
});
chunkById() is safe for mutations and avoids the offset-drift bug. Prefer it by default.
lazy() and lazyById(): PHP Generators Over Eloquent
Introduced in Laravel 8, lazy() wraps chunkById() in a PHP generator and returns a LazyCollection. You iterate a single stream of models without holding more than one chunk in memory at a time.
User::where('active', true)
->lazy(200)
->each(function (User $user) {
// Only 200 models hydrated at any moment
$user->notify(new WeeklyDigest);
});
Because LazyCollection is Enumerable, you can chain higher-order methods:
User::lazy()
->filter(fn($u) => $u->isEligible())
->map(fn($u) => $u->toExportArray())
->each(fn($row) => $csv->writeRow($row));
Filter and map are evaluated lazily — no intermediate array is allocated.
lazyById() is the explicit variant that guarantees keyset pagination under the hood. Use it when you need to be explicit or when the default chunk size of lazy() (1000) is too large for your row width.
cursor(): True Server-Side Cursor
cursor() uses PDO's PDO::FETCH_LAZY to stream rows one at a time from a single query. No chunking, no repeated queries.
foreach (User::cursor() as $user) {
// One model in memory at a time
}
Trade-offs:
- The database connection is held open for the entire iteration.
- On MySQL with
mysqlnd, the full result set is buffered client-side anyway unless you disable buffering — which requires careful PDO configuration. - No safe mutation inside the loop (same offset-drift risk as
chunk()).
For PostgreSQL, server-side cursors behave as expected. For MySQL in most Laravel setups, lazyById() is safer and often faster.
Cursor Pagination for APIs
For paginated HTTP responses, cursorPaginate() replaces numeric OFFSET with an opaque cursor encoding the last-seen keyset:
// Controller
$users = User::orderBy('id')->cursorPaginate(25);
return UserResource::collection($users);
The JSON response includes next_cursor and prev_cursor tokens. This is O(log n) per page regardless of depth — critical when clients page deep into millions of rows.
{
"data": [...],
"next_cursor": "eyJpZCI6MjUwMH0",
"next_page_url": "/api/users?cursor=eyJpZCI6MjUwMH0"
}
Cursor pagination requires a stable, unique sort column. Composite cursors (e.g., created_at + id) are supported via multi-column orderBy.
Choosing the Right Tool
| Scenario | Recommended API |
|---|---|
| Background job processing with mutations | chunkById() |
| Read-only streaming with collection ops | lazy() / lazyById() |
| Single-pass export, no mutations | cursor() (PostgreSQL) |
| Deep-paginated REST API | cursorPaginate() |
Key Takeaways
- Never use
chunk()with mutations on the sort column — usechunkById(). lazy()ischunkById()wrapped in a generator; prefer it for readable pipelines.cursor()holds an open connection and is only truly streaming on PostgreSQL.cursorPaginate()eliminates O(n) offset cost for API pagination at depth.- Always add an index on the cursor column — keyset pagination is only fast with one.