Menu

Post image 1
Post image 2
Post image 3
1 / 3
0

Laravel chunk() vs cursor() vs lazy() — Handle Large Data Without Crashing Your Server

DEV Community: php·codebysuraj·3 days ago
#GyGrYj43
#dev#user#fullscreen#memory#cursor#photo
Reading 0:00
15s threshold

If you've ever tried to process thousands of rows in Laravel and got a memory error or server timeout — this article is for you. I learned this the hard way when a large CSV export caused Apache timeout errors in production. Here's what I found out. The Problem // ❌ This will crash on large tables $users = User :: all (); foreach ( $users as $user ) { // process... } Enter fullscreen mode Exit fullscreen mode all() loads every row into memory at once. On 100,000+ rows, your server will run out of memory. 1. chunk() — Process in Batches User :: chunk ( 500 , function ( $users ) { foreach ( $users as $user ) { // processes 500 rows at a time } }); Enter fullscreen mode Exit fullscreen mode ✅ Memory stays low ✅ Good for background jobs ⚠️ Don't modify/delete rows inside chunk() — it can skip records ⚠️ Runs multiple SQL queries Use when: sending emails in batches, background processing 2.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More