What is Chunking in Eloquent and when to use it?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Laravel deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Chunking processes large database result sets in smaller batches to avoid exhausting PHP memory. User::chunk(200, function($users) { foreach ($users as $user) { /* process */ } }) executes SELECT queries with LIMIT/OFFSET 200 records at a time. If you modify records being chunked (update/delete), use chunkById() instead — it uses cursor-based pagination (keyed on the primary key) rather than offset, which is both faster and safe when modifying records. For maximum efficiency: User::cursor() returns a lazy collection using PHP generators — only one model is in memory at a time (reads row-by-row using PDO cursor). For write-heavy operations on millions of rows, combine chunking with queue jobs for parallel processing. Never load millions of records with User::all().

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Laravel codebase.