Performance Laravel 8 Laravel 9 Laravel 10 Laravel 11 Laravel 12

Memory Limit Exhausted in Laravel - How to Fix

This error occurs when a PHP script tries to use more memory than allowed by the memory_limit setting.

The Error

Error Message
Allowed memory size exhausted

Common Causes

  1. 1 Loading too many Eloquent models into memory
  2. 2 Processing large files without streaming
  3. 3 Memory leaks in loops
  4. 4 Not using lazy collections or chunking
  5. 5 Debug tools enabled in production

Solutions

1

Use chunking for large datasets

PHP
// Instead of loading all records
$users = User::all(); // Bad for large datasets

// Use chunk to process in batches
User::chunk(1000, function ($users) {
    foreach ($users as $user) {
        // Process each user
    }
});
2

Use lazy collections

PHP
// Memory efficient iteration
User::lazy()->each(function ($user) {
    // Process one at a time
});

// Or use cursor
foreach (User::cursor() as $user) {
    // Hydrates one model at a time
}
3

Increase memory limit if needed

PHP
// In your script
ini_set('memory_limit', '512M');

// Or in php.ini
memory_limit = 512M
4

Stream large file downloads

PHP
return response()->streamDownload(function () {
    $handle = fopen('large-file.csv', 'r');
    while (!feof($handle)) {
        echo fgets($handle);
    }
    fclose($handle);
}, 'download.csv');

Need Help With Your Laravel Project?

I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.

Hafiz Riaz

About Hafiz

Senior Full Stack Developer. I build production software with Laravel, Filament, Vue, and AI integrations, and write about the real decisions behind shipping it.

Get in touch →

Related Errors