Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anonymouse703's avatar

Allowed memory size of 268435456 bytes exhausted (tried to allocate 16777248 bytes)

I got this error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 16777248 bytes) even if I add PHP_MEMORY_LIMIT=2G in .env

I have this thousands of data and I want to chuck data in to export

this is the controller

  public function export()
    {
        return Excel::download(new PlayerExport, 'users.xlsx');
    }

The export

<?php

namespace App\Exports;

use App\Models\Player;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;

class PlayerExport implements FromCollection, WithMapping
{

    public function collection()
    {
        return Player::all();
    }

    public function chunk()
    {
        return 10;
    }


    public function map($player): array
    {
        return [
            $player->name,
            $player->email,
            $player->username,
            $player->minerals,
            $player->experiences,
            $player->energies,
            $player->referral_points,
            $player->mmr,
            $player->golds,
        ];
    }

}
0 likes
6 replies
Talinon's avatar

@anonymouse703 First of all, setting PHP_MEMORY_LIMIT will have no effect within the .env file. This is not a Laravel framework environment variable, but rather a PHP configuration. If you wish to increase the amount of memory that PHP is allowed to consume, you will find that option within the php.ini. If you need to find where your php.ini file is located, run this command:

php --ini

It is important to note that if you're using queues, you will also want to make sure you update the memory limit within the CLI php.ini file as well.

To my knowledge, there is no chunk() method within that package. Instead, I think you're looking for querySize() for exporting. Be sure to implement the WithCustomQuerySize concern. You also probably want to use FromQuery, so that the chunking can be done for you:

use App\Models\Player;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithCustomQuerySize;

class PlayerExport implements FromQuery, WithMapping, WithCustomQuerySize
{

// ...

Finally, you may also set a default chunk size within the config/excel.php file. As the documentation states, you might have to run some tests to find the sweet spot for an appropriate chunk size.

anonymouse703's avatar

@Talinon I have this updated code where I can download 10,000 below data but if more than 10,000 records are will error

local.ERROR: Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes) {"userId":16,"exception":"[object] (Symfony\Component\ErrorHandler\Error\FatalError(code: 0): Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes) at /var/www/admin-backend/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php:3318)

code that working right now for 10,000 records below

<?php

namespace App\Exports;

use App\Models\Pvp;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\RemembersChunkOffset;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class PvpExport implements FromQuery, WithStyles, WithHeadings, ShouldAutoSize, WithChunkReading
{
    use Exportable;
    use RemembersChunkOffset;

    private string $writerType = Excel::XLSX;

    protected $startDate;
    protected $endDate;
    protected $mode;

    public function __construct($startDate, $endDate, $mode)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->mode = $mode;
    }

    public function query()
    {
        $query = Pvp::select(
            'id',
            'match_id',
            'player_id_1',
            'player_id_2',
            'winner_id',
            'room_id',
            'type',
            'rake',
            'player_1_level_1_id',
            'player_1_level_2_id',
            'player_2_level_1_id',
            'player_2_level_2_id',
            'player_1_level_1_commission',
            'player_1_level_2_commission',
            'player_2_level_1_commission',
            'player_2_level_2_commission',
            'gold_reward',
            'mmr',
            'mmr_enabled',
            'ends_at',
            'disbursement_completed_at',
            'waiting_time'
        )
            ->when($this->mode !== 'all', function ($query) {
                return $query->where('type', $this->mode);
            })
            ->when($this->startDate && $this->endDate, function ($query) {
                return $query->whereDate('created_at', '>=', $this->startDate)
                    ->whereDate('created_at', '<=', $this->endDate);
            });

        return $query;
    }

    public function headings(): array
    {
        return [
            'ID',
            'Match ID',
            'Player ID 1',
            'Player ID 2',
            'Winner ID',
            'Room ID',
            'Type',
            'Rake',
            'Player 1 Level 1 ID',
            'Player 1 Level 2 ID',
            'Player 2 Level 1 ID',
            'Player 2 Level 2 ID',
            'Player 1 Level 1 Commission',
            'Player 1 Level 2 Commission',
            'Player 2 Level 1 Commission',
            'Player 2 Level 2 Commission',
            'Gold Reward',
            'MMR',
            'MMR_enabled',
            'Ends At',
            'Disbursement Completed At',
            'Waiting Time',
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
        ];
    }

    public function chunkSize(): int
    {
        return 1000; // Adjust the chunk size as per your needs
    }

}
tangtang's avatar

@anonymouse703

Use Laravel Eloquent Cursor: Laravel provides the cursor() method, which allows you to iterate over a large result set without loading the entire result into memory at once. This method is more memory-efficient than chunking

for sample :

public function query()
{
    $query = Pvp::select(/* Your columns here */)
        ->when($this->mode !== 'all', function ($query) {
            return $query->where('type', $this->mode);
        })
        ->when($this->startDate && $this->endDate, function ($query) {
            return $query->whereDate('created_at', '>=', $this->startDate)
                ->whereDate('created_at', '<=', $this->endDate);
        });

    return $query->cursor(); // this is the updated code
}
anonymouse703's avatar

@tangtang I have no data in the dowloaded excel file

  public function query()
    {
        $query = Pvp::select(
            'id',
            'match_id',
            'player_id_1',
            'player_id_2',
            'winner_id',
            'room_id',
            'type',
            'rake',
            'player_1_level_1_id',
            'player_1_level_2_id',
            'player_2_level_1_id',
            'player_2_level_2_id',
            'player_1_level_1_commission',
            'player_1_level_2_commission',
            'player_2_level_1_commission',
            'player_2_level_2_commission',
            'gold_reward',
            'mmr',
            'mmr_enabled',
            'ends_at',
            'disbursement_completed_at',
            'waiting_time'
        )
            ->when($this->mode !== 'all', function ($query) {
                return $query->where('type', $this->mode);
            })
            ->when($this->startDate && $this->endDate, function ($query) {
                return $query->whereDate('created_at', '>=', $this->startDate)
                    ->whereDate('created_at', '<=', $this->endDate);
            })->cursor();

        return $query;
    }
tangtang's avatar

@anonymouse703

			->when($this->mode !== 'all', function ($query) {
                return $query->where('type', $this->mode);
            })
            ->when($this->startDate && $this->endDate, function ($query) {
                return $query->whereDate('created_at', '>=', $this->startDate)
                    ->whereDate('created_at', '<=', $this->endDate);
            })->cursor();

have you try the cursor() in return

			->when($this->mode !== 'all', function ($query) {
                return $query->where('type', $this->mode);
            })
            ->when($this->startDate && $this->endDate, function ($query) {
                return $query->whereDate('created_at', '>=', $this->startDate)
                    ->whereDate('created_at', '<=', $this->endDate);
            });

 return $query->cursor();

Please or to participate in this conversation.