What is Chunking in Eloquent and when to use it?
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().