Back to Error Center

Allowed memory size exhausted

Error Message

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2048 bytes)

Cause

The script consumed more memory than PHP's memory_limit allows. Common when loading large datasets, processing files, or using memory-intensive operations.

Solution

Increase memory_limit in php.ini. Better: process data in smaller chunks, use generators (yield), or use cursor-based queries instead of loading everything into memory.

Code Example

Fix
// Increase memory limit (temporary)
ini_set('memory_limit', '256M');

// Better: use generators for memory efficiency
function getPostIds()
{
    $query = DB::table('posts')->select('id')->cursor();
    foreach ($query as $row) {
        yield $row->id;
    }
}

// Use cursor for large datasets
$posts = Post::cursor();
foreach ($posts as $post) {
    $this->processPost($post); // Processes one at a time
}

// Chunk for batch processing
Post::chunk(100, function ($posts) {
    foreach ($posts as $post) {
        $this->processPost($post);
    }
});

Debugging Steps

  1. Identify which code consumes the most memory
  2. Check the size of datasets being loaded
  3. Profile with xdebug or clockwork
  4. Check for memory leaks in loops

Prevention

Use cursor() or chunk() for large datasets. Process data in batches. Avoid loading entire collections into memory. Use generators where possible.