0

Situation: Array index is right. And dd($row[5]) shows me "email address" from a record - work fine.

However on assigning it ($row[5]) to email field of the object, Laravel shows: ErrorException - Undefined offset: 5

Here is my code:

$file = $request->file('file');
$csvData = file_get_contents($file);
$rows = array_map('str_getcsv', explode("\n", $csvData));

foreach ($rows as $row) {
    //dd($row[5]); // shows me email
    $subscriber = new Subscriber;
    $subscriber->email = $row[5]; // Shows: ErrorException - Undefined offset: 5
    $subscriber->first_name = $row[3];
    $subscriber->save();
}

Here's ddd($row);

array:7 [▼
  0 => "1"
  1 => "2019-02-27 01:01:52"
  2 => "mailchimp"
  3 => "Name"
  4 => "Lastname"
  5 => "[email protected]"
  6 => "EN"
]

Any ideas what's wrong?

1
  • I think there are some line without index 5. You use dd() only print first line. Commented Nov 19, 2019 at 23:44

1 Answer 1

1
  1. dd() will print message. and exit(), so you just print at first loop. It can be without index 5 at second loop.

  2. Don't save() records in each loop, that take more cost times in db; Try to put them in array, and insert them at once.

  3. If you don't want to save that records without email just check the row and don't put it in array.

PS: If you want to rollback when one record failed, try to use transaction

Your code would like this:

$file = $request->file('file');
$csvData = file_get_contents($file);
$rows = array_map('str_getcsv', explode("\n", $csvData));

$arr = array();
// dd($row)  // Here you can see the rows which without index 5.
foreach ($rows as $row) {
    $sub = [];
    $sub['email'] = isset($row[5])? $row[5]: ''; 
    $sub['first_name'] = isset($row[3])? $row[3]: '';
    $arr []= $sub;
}
Subscriber::insert($arr);

Or

$arr = array();
foreach ($rows as $row) {
    $sub = [];
    if (count($row) > 5) {
            $sub['email'] = $row[5]; 
            $sub['first_name'] = $row[3];
            $arr []= $sub;
    }
}
Subscriber::insert($arr);
Sign up to request clarification or add additional context in comments.

4 Comments

Can i remove the line $arr []= $sub; and change the last line to Subscriber::insert($sub);?
@Vadim No, that will insert sql at every loop
It should not insert at every loop if Subscriber::insert($sub); is outside the loop. Or i missing something here?
@Vadim Put it outside, and insert array, this will change to one mysql query: insert into table (email, name) values (sub1_email, sub1_name), (sub2_email, sub2_name),

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.