Laravel Excel ErrorException Undefined offset: 0

2.8k views Asked by At

Trying to import excel data to my mysql db and getting ErrorException Undefined offset: 0.

Tried using var_dump($row) to check the array of the row of the data. It looks off and not sure how to make the data shows nicely so that able to pass to db.

array(5) { ["a"]=> string(1) "B" ["white"]=> string(5) "Green" ["example1_at_gmailcom"]=> string(18) "[email protected]" [60123456789]=> int(60162313142) [5]=> int(5) }

This is my excel data:

enter image description here

Model

 public function model(array $row)
{
    var_dump($row);
    return new ContactList([
        'first_name' => $row[0],
        'last_name' => $row[1],
        'email' => $row[2],
        'phone' => $row[3],
        'group_id' => $row[4],
    ]);
}

I already tried using replacing the $row[] with string and it works perfectly storing the data into my db.

Controller

if($request->hasFile('selected_file')){

            $file = $request->file('selected_file');
            Excel::import(new ContactListsImport, $file);


            return redirect()->back()->with('success', 'Data saved successfully!');
        }
1

There are 1 answers

2
Rwd On BEST ANSWER

You need to remove the WithHeadingRow interface from your Import class to use numeric indexes for the array.

As per the documentation, when your Import class implements WithHeadingRow it will use the first row for the indexes of the array and in turn remove it from the rows that are provided.