How to skip first row when importing file

LDUBBS picture LDUBBS · Jun 23, 2019 · Viewed 10.4k times · Source

I'm trying to import an .xlsx file in Laravel version 5.7 using Maatwebsite-excel version 3.1. What I want to achieve is to skip the first row of the file to avoid importing column headers in my database.

I've tried to use version 2 syntax, calling the skip() method.

public function voter_import(Request $request)
{
    if (empty($request->file('file')->getRealPath())) 
    {
        return back()->with('success','No file selected');
    }
    else 
    {
        Excel::import(new VotersImport, $request->file('file'))->skip(1);
        return response('Import Successful, Please Refresh Page');
    }
}

class VotersImport implements ToModel
{
public function model(array $row)
   {
    return new Voter([
      'fname'          =>  $row[0],
      'lname'          =>  $row[1],
      'phone'          =>  $row[2],
      'gender'         =>  $row[3],
      'state'          =>  $row[4],
      'occupation'     =>  $row[5],
      'address'        =>  $row[6],
      'vin'            =>  $row[7],
      'dob'            =>  $row[8],
      'campaign_id'    =>  $row[9],
    ]);
   }
}

error message:

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

Answer

Robbin Benard picture Robbin Benard · Jun 24, 2019

you can implement the StartingRow

use Maatwebsite\Excel\Concerns\WithStartRow;

class VotersImport implements ToModel, WithStartRow
{
    /**
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
}

Another option would be to use HeadingRow https://docs.laravel-excel.com/3.1/imports/heading-row.html