laravelmaatwebsite-excel

How to skip blank rows in maatwebsite-excel 3.1 for model-way import on Laravel


I'm working on laravel project with maatwebsite-exvel 3.1 to import excel file from file uploding method. This is my StudentsImport class.

public function model(array $row)
{
    return new Student([
        'school_uuid' => Auth::user()->school_uuid,
        'cardid'     => $row[0],
        'prefix'    => $row[1], 
        'name'    => $row[2], 
        'lastname'    => $row[3], 
        'dob'    => $row[4], 
        'address'    => $row[5], 
        'phone'    => $row[6], 
    ]);
}

And below is controller.

 Excel::import(new StudentsImport,  $request->file('file'));

Code work fine. I can import excel's data to database but blank rows also imported. I would like to filter/validate to skip these blanks before put to database. Any advice or guidance on this would be greatly appreciated, Thanks


Solution

  • I use a workaround which helps in my case. Validation is extended by nullable on all rows to avoid errors and then In the method, I have added below code and it worked

    public function model(array $row) 
    {
      if(!array_filter($row)) {
         return null;
      } 
    
      // your code will be here
       return new Student([
            'school_uuid' => Auth::user()->school_uuid,
            'cardid'     => $row[0],
            'prefix'    => $row[1], 
            'name'    => $row[2], 
            'lastname'    => $row[3], 
            'dob'    => $row[4], 
            'address'    => $row[5], 
            'phone'    => $row[6], 
        ]);
    

    and skip these rows at this point. Not really happy with this as I cannot return an useful error message but as I found no solution the best way to get the code running. I found this from here. https://github.com/SpartnerNL/Laravel-Excel/issues/1861#issuecomment-520753182