When PHP runs out of memory it is tempting to just raise memory_limit. But the real cause is usually loading too much data at once. Fix the pattern first.
The Error
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate ...)
Cause: Loading Everything Into Memory
// ❌ Loads all rows at once
$users = User::all();
foreach ($users as $user) { /* ... */ }
// ✅ Process in chunks of 500
User::chunk(500, function ($users) {
foreach ($users as $user) { /* ... */ }
});
// ✅ Or lazy-stream a cursor
foreach (User::cursor() as $user) { /* ... */ }Exporting Big Files? Stream It
Build CSVs with a streamed response instead of concatenating a giant string in memory. Laravel's response()->streamDownload() writes row by row.
Last Resort: Raise the Limit
ini_set('memory_limit', '512M'); // for one heavy script onlyWarning
Raising memory_limit globally just delays the crash and hides O(n) memory growth. Chunk first; raise the limit only for genuinely large one-off jobs.
