# PHP Fatal error: Allowed memory size of 134217728 bytes exhausted — how to fix it

> PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate N bytes) means one PHP process reached its memory_limit, here 128M, PHP's default. Raise the limit for one run with php -d memory_limit=512M, in php.ini, or for Composer with COMPOSER_MEMORY_LIMIT; then fix what filled it, usually a query that loads every row at once or a response built in memory. In Laravel, chunk, lazy and streamed responses keep memory flat.

Source: https://livops.dev/en/guides/error-php-allowed-memory-size-exhausted

By Livops team, the people who build and run Livops. Updated 1 December 2026.

The error, from a command line or a web request's log (the numbers and paths vary):

```text
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /var/www/html/app/Console/Commands/ExportUsers.php on line 31
```

Composer prints the same message when it runs out[6], and WordPress names it as the reason for its own memory setting[11]. This page explains what the two numbers mean, how to find which limit applies, how to raise it for one run, in `php.ini`, in code, for Composer and for WordPress, and then the fixes that make the error go away for good: loading rows in chunks, streaming large responses and keeping queue workers lean.

## What does the error mean?

`memory_limit` is the maximum amount of memory, in bytes, that a script is allowed to allocate. It exists so that a badly written script cannot eat up all the memory on a server. Its default is `128M`, and `-1` means no limit[1]. In PHP's shorthand, `1M` is 1048576 bytes[2], so 128M is exactly **134217728 bytes**: the number in the message is the default, untouched.

PHP writes the message as `Allowed memory size of <limit> bytes exhausted (tried to allocate <size> bytes)`, where the first number is the limit and the second is the single allocation that would have crossed it[3]. A small second number does not mean a small problem: the process had already used nearly all of its memory, and this allocation was the last straw.

| The first number | Is | Usually set by |
| --- | --- | --- |
| `134217728` | 128M | PHP's default[1] |
| `268435456` | 256M | Someone raised it once |
| `536870912` | 512M | Someone raised it twice |
| `1610612736` | 1.5G | Composer, which raises its own limit to 1.5G[6] |

Two newer details. As of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35, `memory_limit` is a soft limit: an allocation that crosses it is in most cases allowed to finish before the fatal error, and a separate hard limit, `memory_hard_limit_percent`, bounds how far it may go over[1]. And since PHP 8.5, a server can cap `memory_limit` with `max_memory_limit`; a higher value is cut down to the cap with a warning[1].

## First, find which limit applies

The command line and the web server can read different configuration files. Check the value the command line gets[6], and which `php.ini` it loads[4]:

```sh
php -r "echo ini_get('memory_limit').PHP_EOL;"
php --ini
```

On Debian-like systems the command line has its own file, for example `/etc/php5/cli/php.ini` in Composer's docs[6], so a web request may run with another value. To see what a request gets, print `ini_get('memory_limit')` from a route. To see how much the code really needs, log `memory_get_peak_usage(true)`, the peak of memory allocated to the script, with `true` for the real size taken from the system[5].

## Raising the limit

Raise it when the work is honest and just bigger than 128M: an import run once, a Composer update, a report. If the error moves to the next round number every month, go to the next section instead.

### For one command

`-d` sets any `php.ini` directive for that run only[4]:

```sh
php -d memory_limit=512M artisan app:import-users
```

### In php.ini

Change it in the file `php --ini` named, for the command line, the web server, or both:

```ini
memory_limit = 512M
```

### In code

`memory_limit` can be changed anywhere, at runtime too[1], so a single heavy script can raise its own limit before the heavy part:

```php
ini_set('memory_limit', '512M');
```

On PHP 8.5 a server's `max_memory_limit` still caps it[1].

### For Composer

Run Composer 2, if possible 2.2.0 or newer; Composer 1 used much more memory[6]. Composer raises its own limit to 1.5G[6]. When even that is not enough, set `COMPOSER_MEMORY_LIMIT`, whose value is used as PHP's `memory_limit`[7], or pass `-d`[6]:

```sh
COMPOSER_MEMORY_LIMIT=-1 composer update
php -d memory_limit=-1 composer.phar update
```

These settings mainly cover Composer and its immediate processes; child processes or external commands it starts may need their own[6].

### For WordPress

Set `WP_MEMORY_LIMIT` in `wp-config.php`, before the line that includes `wp-settings.php`; `WP_MAX_MEMORY_LIMIT` sets the limit for the admin area[11]:

```php
define( 'WP_MEMORY_LIMIT', '256M' );
```

It raises PHP's memory only for WordPress. By default WordPress tries to raise it to 40MB on a single site and 64MB on multisite, and some hosts do not allow raising it at all[11]. WordPress's own docs warn that a higher limit can hide the cause, often too many memory-hungry functions on one action, which belong in a cron job[11].

## The real fixes

### Load rows in batches, not all at once

The most common cause in Laravel is `Model::all()` or `->get()` on a big table. Laravel's docs say an app may run out of memory loading tens of thousands of records that way[8]. `chunk` passes the rows to a callback a batch at a time, one query per batch; when you update the column you filter on, use `chunkById`, which pages by `id`[8]:

```php
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;

User::where('active', false)->chunkById(500, function (Collection $users) {
    foreach ($users as $user) {
        $user->update(['active' => true]);
    }
}, column: 'id');
```

`lazy` runs the same batched queries but gives you one stream to loop over[8]:

```php
foreach (User::lazy() as $user) {
    // one batch in memory at a time
}
```

`cursor` runs a single query and holds one model in memory at a time, but cannot eager load relationships, and on very large results it can still run out because PHP's PDO driver buffers the raw results; Laravel's docs point to `lazy` there[8].

### Stream large responses

An export built as one string or one array holds everything in memory before the first byte is sent. A streamed response sends data as it is generated, which Laravel's docs say significantly reduces memory use for very large responses[9]. `streamDownload` turns output into a download without writing it to disk first[9]:

```php
use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/users.csv', function () {
    return response()->streamDownload(function () {
        $out = fopen('php://output', 'w');
        foreach (User::lazy() as $user) {
            fputcsv($out, [$user->id, $user->email]);
        }
        fclose($out);
    }, 'users.csv');
});
```

For JSON, `response()->streamJson(['users' => User::cursor()])` sends a large dataset progressively[9].

### Keep queue workers lean

A queue worker is long-lived and keeps the booted application in memory, and static state is not reset between jobs[10]. Memory that grows a little per job ends in this error after a few hours. `--memory` is the limit in megabytes at which the worker exits, 128 by default, or a percentage of `memory_limit`; `--max-jobs` and `--max-time` make it exit after a number of jobs or seconds, releasing what it accumulated[10]. Something has to start it again, such as Supervisor[10]:

```sh
php artisan queue:work --memory=256 --max-jobs=500
```

Free heavy resources after each job; Laravel's docs give `imagedestroy` after GD image work as the example[10].

## How to confirm the fix

Print the peak before and after the change, with the same data[5]:

```php
logger()->info('peak MB: '.round(memory_get_peak_usage(true) / 1048576));
```

If the peak stays flat as the table grows, the code is fixed; if it grows with the table, a raised limit only buys time.

## On Livops

- **Two limits, two messages.** This error is PHP's `memory_limit` inside one process. When the service itself runs out of memory, it is stopped, and **Logs** says `Killed`, or exit code 137; see [Out of memory](https://livops.dev/en/docs/error-start#out-of-memory). Raising `memory_limit` above the service's memory turns the first message into the second.
- **The service's memory** is a tier: 256, 512, 1024 or 2048 MiB. `memory` in `livops.json` is read when the project is created; after that the tier is changed in the project's settings, and it is part of what you pay for. See [Frameworks and livops.json](https://livops.dev/en/docs/frameworks).
- **The assistant** can propose changing a service's memory as a card; it waits for your click. See [AI assistant](https://livops.dev/en/docs/assistant).
- **Where the error shows.** The start command Livops writes for a Laravel app begins with `LOG_CHANNEL=${LOG_CHANNEL:-stderr}`, so what Laravel logs is on the service's **Logs** tab.
- **Exports.** `/tmp` is wiped on every restart and holds 128 MB, so a large file built there first can fail too; stream it instead, as above. See [Files and data](https://livops.dev/en/docs/files).

The full Laravel setup on Livops, with the worker and the scheduler: [Laravel hosting](https://livops.dev/en/hosting/laravel-hosting); plain PHP: [PHP hosting](https://livops.dev/en/hosting/php-hosting). When Composer stops before memory is ever the problem: [Your requirements could not be resolved to an installable set of packages](https://livops.dev/en/guides/error-composer-requirements-could-not-be-resolved).

## Questions

**Why exactly 134217728 bytes?**

It is 128M written out in bytes. In PHP's shorthand one M is 1048576 bytes, and 128 times that is 134217728. 128M is the default memory_limit, so this number means nobody changed the limit for that process.

**The message says tried to allocate only 20480 bytes. Why is that too much?**

The second number is only the one allocation that would have crossed the limit, not the total. By then the process had already used almost all of its 128M. Look for what filled the memory before that line, not at the line itself.

**Is memory_limit = -1 safe?**

It removes PHP's limit. For a one-off command such as a Composer update on your own machine that is common, and Composer's docs show it. For web requests and long-running workers it is risky: the limit exists so that one badly written script cannot eat all the memory on the server.

**Why does Composer still fail after I raised the limit?**

Composer already raises its own limit to 1.5G, so a Composer error usually shows 1610612736 bytes, and only a higher value or -1 helps. COMPOSER_MEMORY_LIMIT and php -d memory_limit cover Composer itself and its immediate processes; an external command Composer starts may need its own setting.

**Should I use chunk, lazy or cursor in Laravel?**

chunk and chunkById pass the rows to a callback a batch at a time, lazy gives you the same batches as one stream, and cursor runs a single query and holds one model at a time. cursor cannot eager load relationships and can still run out of memory on very large results because PDO buffers them, so Laravel's docs point to lazy for those.

**What is the difference between this error and Killed or exit code 137?**

This error is PHP's own limit, memory_limit, inside one PHP process. Killed or exit code 137 means the whole container or machine ran out, and the operating system stopped the process. Raising memory_limit above the memory the machine has turns the first into the second.

**How do I give a PHP app more memory on Livops?**

Change the service's memory tier in its settings: 256, 512, 1024 or 2048 MiB. The tier is part of what you pay for. The assistant can also propose the change as a card, which waits for your click.

## Sources

1. [PHP manual — Description of core php.ini directives (memory_limit)](https://www.php.net/manual/en/ini.core.php). Checked 1 December 2026.
2. [PHP manual — FAQ, Using PHP (shorthand byte values)](https://www.php.net/manual/en/faq.using.php). Checked 1 December 2026.
3. [PHP source — Zend/zend_alloc.c](https://github.com/php/php-src/blob/master/Zend/zend_alloc.c). Checked 1 December 2026.
4. [PHP manual — Command line options](https://www.php.net/manual/en/features.commandline.options.php). Checked 1 December 2026.
5. [PHP manual — memory_get_peak_usage](https://www.php.net/manual/en/function.memory-get-peak-usage.php). Checked 1 December 2026.
6. [Composer docs — Troubleshooting (Memory limit errors)](https://getcomposer.org/doc/articles/troubleshooting.md). Checked 1 December 2026.
7. [Composer docs — Command-line interface (COMPOSER_MEMORY_LIMIT)](https://getcomposer.org/doc/03-cli.md). Checked 1 December 2026.
8. [Laravel docs — Eloquent, chunking and cursors (13.x, docs source)](https://github.com/laravel/docs/blob/13.x/eloquent.md). Checked 1 December 2026.
9. [Laravel docs — HTTP Responses, streamed responses (13.x, docs source)](https://github.com/laravel/docs/blob/13.x/responses.md). Checked 1 December 2026.
10. [Laravel docs — Queues, resource considerations (13.x, docs source)](https://github.com/laravel/docs/blob/13.x/queues.md). Checked 1 December 2026.
11. [WordPress Developer Resources — Editing wp-config.php (Increasing memory allocated to PHP)](https://developer.wordpress.org/advanced-administration/wordpress/wp-config/). Checked 1 December 2026.
