0

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!');
        }
10
  • 1
    you are dumping the array you are getting ... do you see a key 0 in it? Commented Oct 10, 2020 at 8:45
  • sry, i am new to this. No i didnt see it but even i removed the vardump i still getting the same error ErrorException Undefined offset: 0 Commented Oct 10, 2020 at 8:47
  • because there is no index 0 as you can see as you dumped the array and there is no key 0 ... you can't access keys of an array that don't exist ... you have an issue here as the first row of this file is being used as the headers (column names), you should look into the documentation to adjust this or not use this behavior Commented Oct 10, 2020 at 8:48
  • Just an FYI, but Laravel using Symfony's VarDumper component so you can use dump() and dd() for a more readable output. Commented Oct 10, 2020 at 8:49
  • What version of Laravel and Laravel Excel are you using? Commented Oct 10, 2020 at 8:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I think this is the reason why
@N.Tec If this has answered your question please may you mark it as accepted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.