Fix "Allowed memory size of 134217728 bytes exhausted" in PHP
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
- Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes)
- Symfony\Component\ErrorHandler\Error\FatalError: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes)
- PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 67108864 bytes) in phar:///usr/local/bin/composer
- PHP Fatal error: Out of memory (allocated 2097152) (tried to allocate 65536 bytes)
The PHP script exceeded its memory_limit (134217728 bytes = 128 MB, the default value). Before raising the limit, find what uses that much memory: most often a query that loads thousands of rows at once, infinite recursion or a large file read in full.
What this error means
PHP gives each request or command a maximum amount of memory, set by the memory_limit directive in php.ini. When the script asks for one more block ("tried to allocate") that would cross that ceiling, PHP stops with a fatal error. The number shown is the limit in bytes: 134217728 is 128 MB, 268435456 is 256 MB. The requested size is often tiny: that allocation is not the problem, everything accumulated before it is. The file and line shown only tell you where the limit was crossed.
Common causes
- Too much data loaded at once:
Model::all()or->get()on a large table, plus eager-loaded relations. - Infinite recursion or loop: an accessor calling itself, circular relations serialized with
toArray(), an observer triggering anothersave(). - Large files in memory:
file_get_contents()orfile()on a big CSV, Excel exports, high-resolution image processing with GD. - Leak in a long-running process: queue worker, query log (
DB::enableQueryLog()) or a debug tool that accumulates data on every iteration. - Composer:
composer updateorcomposer requiremay need more memory to resolve a large dependency tree.
Step-by-step fix
-
Read the limit and context
Note the file and line, then check the actual limit and the loaded
php.ini. Careful: the CLI and PHP-FPM often use two differentphp.inifiles.# macOS / Linux php -i | grep memory_limit php --ini # Windows (PowerShell) php -i | findstr memory_limit -
Process data in batches
Replace
all()orget()withchunkById()orlazy(): Laravel loads rows in batches instead of keeping everything in memory.use App\Models\User; User::where('active', true)->chunkById(1000, function ($users) { foreach ($users as $user) { // process $user } }); // or one model at a time foreach (User::where('active', true)->lazy() as $user) { // process $user } -
Stream large files
Read a file line by line with
fopen()andfgetcsv()instead of loading it entirely withfile()orfile_get_contents().$handle = fopen(storage_path('app/import.csv'), 'r'); while (($row = fgetcsv($handle)) !== false) { // process $row } fclose($handle); -
Rule out infinite recursion
If the limit is hit even with little data, look at the stack trace: the same function repeated hundreds of times means recursion. Check accessors,
$appends,$withand relations serialized in both directions. -
Measure memory usage
Log memory usage at several points to find the peak. For workers, cap memory and the number of jobs so they restart cleanly.
logger()->info('memory', [ 'current_mb' => round(memory_get_usage(true) / 1048576, 1), 'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 1), ]); // queue worker: php artisan queue:work --memory=256 --max-jobs=500 -
Raise the limit only if the need is real
For a one-off command, pass the limit as an option. For the server, change
memory_limitin the rightphp.inithen restart PHP-FPM (the service name depends on your PHP version). Avoid-1(unlimited) on a production web server: a runaway request can eat all the server RAM.# one-off command php -d memory_limit=512M artisan app:import-users # php.ini (web): memory_limit = 256M, then sudo systemctl restart php8.4-fpm # Composer (macOS / Linux) COMPOSER_MEMORY_LIMIT=-1 composer update # Composer (Windows PowerShell) $env:COMPOSER_MEMORY_LIMIT='-1'; composer update
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Use
chunkById(),lazy()orcursor()for any job that walks a whole table, and paginate displayed lists. - Run workers with
--memoryand--max-jobs, plus a supervisor (Supervisor, systemd) that restarts them. - Only enable the query log and debug tools locally or temporarily, never inside a long-running process.
Frequently asked questions
How many MB is 134217728 bytes?
134217728 bytes = 128 MB (128 × 1024 × 1024). 268435456 = 256 MB, 536870912 = 512 MB.
I raised memory_limit but the error still shows 128 MB, why?
You probably edited a different php.ini than the one in use (CLI or FPM), or PHP-FPM was not restarted. php --ini and a phpinfo() page show the file actually loaded.
Why does Composer run out of memory?
Dependency resolution can need a lot of memory. Run COMPOSER_MEMORY_LIMIT=-1 composer update for that command only, and update Composer with composer self-update.
Useful tools for this error
More PHP & Laravel errors
- Fix "419 Page Expired" in Laravel (CSRF token mismatch)
- Fix "Target class [X] does not exist" and "Class not found" in Laravel
- Fix "SQLSTATE[HY000] [2002] Connection refused" in Laravel
- Fix "No application encryption key has been specified" in Laravel
- Fix "Your requirements could not be resolved to an installable set of packages" (Composer)
- Fix "laravel.log could not be opened in append mode: Permission denied"
- Fix "Vite manifest not found at: public/build/manifest.json" in Laravel