Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip first row when importing file

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()

like image 337
LDUBBS Avatar asked Jun 23 '19 18:06

LDUBBS


1 Answers

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

like image 51
Robbin Benard Avatar answered Sep 28 '22 16:09

Robbin Benard