Search code examples
laravelmaatwebsite-excel

Call to undefined method Maatwebsite\Excel\Excel::filter()


Please I need quick help. Am trying to import a large excel file in chunk using this code as per the documentation:

Excel::filter('chunk')
    ->load('file.csv')
    ->chunk(250, function($results)
    {
        foreach($results as $row)
        {
            // do stuff
        }
    }); 

However, I am getting this error which I can't understand.

Call to undefined method Maatwebsite\Excel\Excel::filter()

I have checked everywhere online and can't find the same error anywhere. Where am I going wrong?


Solution

  • Please, implement the interface WithChunkReading. And return the chunkSize (in bytes) from the method named chunkSize. For example:

    namespace App\Imports;
    
    use App\User;
    use Maatwebsite\Excel\Concerns\ToModel;
    use Maatwebsite\Excel\Concerns\WithChunkReading;
    
    class UsersImport implements ToModel, WithChunkReading
    {
        public function model(array $row)
        {
            return new User([
                'name' => $row[0],
            ]);
        }
        
        public function chunkSize(): int
        {
            return 1000;
        }
    }
    

    And call the import method like below from your controller method:

    return Excel::import(new UsersImport, 'users.xlsx');
    

    N.B: This should work from the laravel-excel version 3.1