You run a script โ an import, a report, a queue job โ and instead of a result PHP kills it on the spot:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 20480 bytes) in /var/www/app/Services/ReportBuilder.php on line 88
There is no partial output, no graceful fallback, and no way to catch the error with a try block. The script simply stops. The instinctive fix is to make the number bigger, and that does work โ until the data grows again and the same error comes back at 2 a.m. instead of 2 p.m. This guide covers both halves: how to raise the limit correctly, and how to fix the code so you stop needing to.
What the error message is actually telling you
Three numbers matter in that message, and one of them misleads people:
- Allowed memory size of 134217728 bytes is your current
memory_limit, in bytes. Divide by 1,048,576 and you get 128M โ the default PHP limit. This is the ceiling for one single process, not for your whole server. - Tried to allocate 20480 bytes is the single allocation that happened to cross the line โ a 20 KB block for one more row. It is not the problem; it is just the straw that broke the camel's back.
- On line 88 is where the limit was hit, which is usually inside the loop that is collecting data โ not necessarily where the memory was wasted. The real cause is often earlier in the code, where the collection started growing.
So the error does not mean "your server has no RAM". It means one PHP process asked for more memory than its configured ceiling allows. The fix is either to raise that ceiling, or to make the process need less โ and in most real cases, the second one is the durable answer.
Step 1: Find the limit that actually applies
PHP has several runtimes on one machine, and each reads its own configuration. Your web app (PHP-FPM) and your command line (CLI) often use completely separate php.ini files. Raising the limit for the web side does nothing for a Composer install or an Artisan command, and the reverse is just as true.
Check the limit in the same runtime that failed:
php --ini # which php.ini files the CLI loads
php -r 'echo ini_get("memory_limit"), PHP_EOL;'
For a web request, drop this into a scratch route or script โ and never leave it on production:
<?php
echo 'memory_limit = ' . ini_get('memory_limit') . PHP_EOL;
echo 'peak so far = ' . round(memory_get_peak_usage(true) / 1024 / 1024, 2) . ' MB' . PHP_EOL;
If php -i says 512M but your Laravel queue job still dies at 128M, you are probably reading the CLI config while the worker runs under Supervisor with a different php.ini, or the web config while the failure is on CLI. Run php --ini to see exactly which files the CLI loads, and use phpinfo() or a route for the web side. memory_get_peak_usage(true) is also worth knowing: it tells you the highest real memory your script actually used, which is the number you should size the limit from โ not a guess.
Step 2: Raise the limit in the right place
Once you know which runtime failed, raise the limit exactly there. The table below covers the common spots:
| Where | How | Scope |
|---|---|---|
php.ini |
memory_limit = 256M |
Everything using that ini file. Restart PHP-FPM or Apache after changing it. |
| Command line | php -d memory_limit=512M script.php |
That one run only |
| In the script | ini_set('memory_limit', '256M'); |
The current request or process |
| FPM pool file | php_admin_value[memory_limit] = 512M |
One pool |
.htaccess |
php_value memory_limit 256M |
Only on mod_php, not FPM. If you get a 500 after adding it, your host blocks the directive โ remove the line. |
| Composer | COMPOSER_MEMORY_LIMIT=-1 composer update |
Composer only |
Two warnings before you raise anything. First, avoid memory_limit = -1 for web requests: the limit is what stops one runaway request from taking down the whole server, so use a real number sized from measurements. Second, 256M is the usual first step and 512M is a reasonable ceiling for a shared site. If 512M is still not enough, that is evidence of a code fault, not of a limit set too low โ move on to step 3 instead of raising it again.
Step 3: Stop collecting everything into memory
Raising the limit hides the problem until the data grows again. The usual patterns that use far more memory than needed all share one shape: a loop that builds an array of every row so a later loop can walk it. Holding 100,000 small rows in an array costs tens of megabytes, and a million rows costs ten times that โ which is why the full run failed.
The fix is to keep one row at a time, which is what a generator does:
<?php
function rows(): Generator
{
for ($i = 0; $i < 1_000_000; $i++) {
yield ['id' => $i, 'email' => "user{$i}@example.com"];
}
}
foreach (rows() as $row) {
// process one row, then let it go
}
The generator version never holds more than one row at a time, so its peak memory stays flat no matter how many rows pass through it. In a database loop the equivalent is fetching row by row instead of calling fetchAll(), and in Laravel it is lazy() or cursor() instead of get():
<?php
// Bad: loads every user into memory at once
$users = User::all();
foreach ($users as $user) {
// ...
}
// Good: streams users one chunk at a time
User::chunk(500, function ($users) {
foreach ($users as $user) {
// ...
}
});
The same idea applies to files. Never read a whole file into a string with file_get_contents() when you only need to process it line by line โ use fopen() with fgets() in a loop so memory stays flat while the file grows.
Step 4: Hunt the real leaks
If the code is not obviously collecting rows, the memory is probably growing somewhere you are not looking. The usual suspects, in order:
- A cache inside a long-running process. Queue workers and import commands run for hours, and anything stored in a static property or a global array accumulates across jobs. Restart the worker regularly, or clear the cache between jobs.
- An N+1 query loading whole models. Loading a relation for every row in a loop pulls far more data than the loop needs. Eager-load with
with(), and select only the columns you actually use. - An image or PDF library holding the whole document. Process in tiles or pages, and free each one with
imagedestroy()or the library's own cleanup call.
Measure before you guess. Put memory_get_peak_usage(true) calls around the suspicious sections and watch which one jumps. The section that jumps is the one to fix โ everything else is noise.
When raising the limit IS the right fix
Not every case is a code problem. Sometimes the job genuinely needs the memory: a large Composer install, a one-off data migration, a big spreadsheet export. In those cases raising the limit is correct โ but raise it only for that one run, with php -d memory_limit=512M on the command line or ini_set() at the top of the script, and leave the global limit where it was.
The same logic applies to the related time limit: if a long job also hits the execution-time wall, the fix follows the same pattern โ find the real limit, raise it for that one job, and fix the code if it keeps growing. I covered that one separately in how to fix the maximum execution time error in PHP.
FAQ
Can I catch this error with try/catch?
No. A fatal error is not an exception, so try/catch cannot catch it. The only defence is to not run out of memory in the first place.
Why does the same script work on my laptop but fail on the server?
Different memory_limit values. Local setups often run with -1 (unlimited) or 512M, while shared hosting commonly sets 128M. Check the limit on the machine that actually runs the script.
Is 1G a safe memory_limit for a web app?
No. One runaway request could then consume 1 GB, and a handful of them at once would take the server down. Size the limit from measured peak usage, and fix the code if the measurement keeps growing.
Does raising the limit in php.ini need a restart?
For PHP-FPM or Apache, yes โ restart the service after editing php.ini. For the CLI, no: every php command reads the file fresh.
The short version
Read the three numbers in the message, find the limit for the runtime that actually failed, raise it in the right place โ and then fix the code. Generators, chunked queries and streaming file reads keep memory flat while your data grows, which is the only fix that still works when the dataset doubles next year.


![How to Fix "Target class [Controller] does not exist" Error in Laravel](https://rajadevsolutions.online/storage/posts/featured-how-to-fix-target-class-does-not-exist-error-in-laravel.jpg)