How to Fix PHP Fatal Error: Allowed Memory Size Exhausted
The "Allowed memory size exhausted" error is one of the most common PHP fatal errors. It occurs when a PHP script uses more memory than the limit configured on your server.
A typical error looks like this:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65536 bytes)or in Laravel:
Symfony\Component\ErrorHandler\Error\FatalError
Allowed memory size of 268435456 bytes exhaustedThis guide explains what causes the error and how to fix it in PHP and Laravel applications.
Why Does This Error Happen?
Every PHP application has a memory limit.
When your script tries to use more memory than allowed, PHP immediately stops execution and throws a fatal error.
Common causes include:
Processing very large datasets
Infinite loops or recursion
Loading thousands of database records
Importing large CSV or Excel files
Image processing
Memory leaks in custom code
Composer or Artisan commands requiring more memory
The goal is not only to increase the memory limit but also to identify why your application needs so much memory.
Step 1: Check Your Current PHP Memory Limit
Create a PHP file:
<?php
phpinfo();Search for:
memory_limitor run from the terminal:
php -i | grep memory_limitYou may see:
memory_limit => 128MStep 2: Increase the PHP Memory Limit
Open your php.ini file and update:
memory_limit = 512MSave the file and restart your web server.
For Apache:
sudo systemctl restart apache2For Nginx with PHP-FPM:
sudo systemctl restart php8.3-fpm
sudo systemctl restart nginxReplace the PHP version with the one installed on your server.
Step 3: Increase Memory Temporarily
If you only need more memory for a specific script:
ini_set('memory_limit', '512M');This change only affects the current request.
Step 4: Check Large Database Queries
A common Laravel mistake is loading every record into memory.
Problem:
$users = User::all();If your table contains hundreds of thousands of rows, PHP may run out of memory.
Better:
User::chunk(1000, function ($users) {
foreach ($users as $user) {
// Process user
}
});Processing records in chunks significantly reduces memory usage.
Step 5: Use Lazy Collections
Instead of:
$orders = Order::all();use:
Order::lazy()->each(function ($order) {
// Process order
});Lazy collections load records as needed instead of loading everything into memory.
Step 6: Optimize File Imports
Importing large CSV or Excel files can quickly exhaust memory.
Instead of reading the entire file at once, process it line by line or in batches.
If you're using Laravel Excel, consider reading data in chunks to reduce memory usage.
Step 7: Check for Infinite Loops
An infinite loop can continuously allocate memory.
Example:
while (true) {
$data[] = rand();
}Since the loop never ends, memory usage keeps increasing until PHP reaches its limit.
Review loops carefully and ensure they have a proper exit condition.
Step 8: Check Recursive Functions
Recursive functions without a stopping condition can consume large amounts of memory.
Problem:
function calculate()
{
calculate();
}Always define a base condition before making another recursive call.
Step 9: Clear Laravel Cache
Corrupted or outdated cache can sometimes contribute to memory-related issues.
Run:
php artisan optimize:clearThen rebuild the cache if needed:
php artisan optimizeStep 10: Composer Memory Issues
Composer can also run out of memory during package installation.
Example:
composer installIf you receive a memory error, temporarily remove the limit:
php -d memory_limit=-1 composer installUse this only for Composer commands—not for production web requests.
Common Laravel Examples
Queue Worker
Long-running queue workers may gradually consume more memory.
Restart workers periodically:
php artisan queue:restartExporting Large Reports
Problem:
$orders = Order::all();Better:
Order::chunk(500, function ($orders) {
// Generate report
});Image Processing
Large image uploads require substantial memory.
Before increasing the PHP memory limit, consider:
Resizing images
Compressing uploads
Processing images asynchronously using queues
Should You Set memory_limit = -1?
You may find advice recommending:
memory_limit = -1This removes the memory limit entirely.
While it can be useful for temporary CLI tasks, it's not recommended for production websites because a faulty script could consume all available server memory and affect other applications.
Instead, increase the limit only as much as necessary and optimize the underlying code.
Final Checklist
If you see:
Allowed memory size exhaustedcheck the following:
✓ Verify your current PHP memory limit
✓ Increase the limit if appropriate
✓ Avoid loading all database records at once
✓ Use chunk() or lazy() for large datasets
✓ Review loops and recursive functions
✓ Optimize file imports and exports
✓ Clear Laravel cache
✓ Restart queue workers if needed
Most memory exhaustion errors are caused by inefficient code rather than a memory limit that's too low. Optimizing database queries and processing data in batches usually provides a long-term solution.
If your PHP or Laravel application is still running out of memory, send me the full error message and the relevant code. I'll help identify the root cause and recommend the best fix.