Laravel Excel Import 記憶體不夠問題

大量資料匯入實出現 Allowed memory size of 1073741824 bytes exhausted 錯誤。

解法參考官網說明,載入並實做 Maatwebsite\Excel\Concerns\WithChunkReading 這個 class,並加上 chunkSize 方法,如下:
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class UsersImport implements ToCollection, WithChunkReading
{
    public function collection(Collection $rows)
    {
        $rows->each(function ($row, $key) {
            if ($key < 1 && $row[0] == '欄位標題') {
                return true;
            }
        });
        
        ...
    }
    
    public function chunkSize(): int
    {
        return 1000;
    }
}
要特別注意第 9 行的判斷,如果使用 chunkSize 後每 1000 筆的第 1 筆都會被跳過,所以要多加上標題內容的判斷,以避免有資料沒有匯入。

留言