Scaleup Infotech
Scaleup Infotech.
Back to Blog
Bug Fixes7 min read

Fix PHP 'Allowed memory size of X bytes exhausted'

Scaleup Infotech

Scaleup Infotech

Software & Marketing Agency

Mar 24, 2026
Fix PHP 'Allowed memory size of X bytes exhausted'
PHPLaravelPerformanceMemory

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

php
// ❌ 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

php
ini_set('memory_limit', '512M'); // for one heavy script only

Warning

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.

Share this article:

Keep Reading

Ready to implement these ideas?

Work With Scaleup Infotech