0

I'm new to the blog and I joined because I have a problem for a while.

The following code is for importing users through a .csv file into a database, but when I try to import users, the following error appears.

8
"Undefined index: name"
"D:\xampp\htdocs\plataforma\app\Http\Controllers\UserController.php"
39
array:7 [▼
  "request" => Request {#43 ▶}
  "validator" => Validator {#257}
  "file" => UploadedFile {#247 ▶}
  "csvData" => """
    name,username,email,password,role,idSede,idManager\r\n
    Claudio Magallan,claudiomg,claudiomagallan@hotmail.com,secret,2,60,0\r\n
    Cristina Vargas,cristyvg,cristyvargas@institutodeventas.com,secret,3,61,4\r\n
    """
  "rows" => array:3 [▶]
  "header" => array:7 [▶]
  "row" => array:7 [▶]
]

I really appreciate your help and I hope you can help with my problem. I attach my controller code.

public function upload(Request $request) {
  $validator = Validator::make($request->all(), [
    'file' => 'required'
  ]);
  if ($validator->fails()) {
    return redirect()
    ->back()
    ->withErrors($validator);
  }
  $file = $request->file('file');
  $csvData = file_get_contents($file);
  $rows = array_map("str_getcsv", explode("\n", $csvData));
  $header = array_shift($rows);
  foreach ($rows as $row) {
    $row = array_combine($header, $row);
    User::create([
      'name' => $row['name'],
      'username' => $row['username'],
      'email'    => $row['email'],
      'password' => bcrypt($row['password']),
      'role'     => $row['role'],
      'idSede'   => $row['idSede'],
      'idManager'=> $row['idManager'],
    ]);
  }
  flash('Users imported');
  return redirect()->back();
}

The error mark the next line code:

'name' => $row['name'],

Regards!

Alan Rincón
  • 3
  • 1
  • 4
  • What did you try so far? – Camilo Dec 07 '18 at 02:38
  • Hi Camilo, I try to import a list of users from a .csv file – Alan Rincón Dec 07 '18 at 02:43
  • What's the result of `dd($row)`? – Camilo Dec 07 '18 at 02:49
  • Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – miken32 Dec 07 '18 at 02:50
  • Camilo... before the line $row = array_combine($header, $row); I get: array:7 [▼ 0 => "Claudio Magallan" 1 => "claudiomg" 2 => "claudiomagallan@hotmail.com" 3 => "secret" 4 => "2" 5 => "60" 6 => "0" ] after one I get: array:7 [▼ "name" => "Claudio Magallan" "username" => "claudiomg" "email" => "claudiomagallan@hotmail.com" "password" => "secret" "role" => "2" "idSede" => "60" "idManager" => "0" ] Hi Miken, yeah looks similar but I used isset before but I didn't have a good result yet. – Alan Rincón Dec 07 '18 at 05:34
  • @AlanRincón attach your csv as well. – amit Dec 07 '18 at 07:10

1 Answers1

1

The following change might work:

$rows = array_map("str_getcsv", explode("\n", $csvData));
$header = array_shift($rows);
array_pop($rows); // delete the element
foreach ($rows as $row) { .. }

Laravel can be easily debugged using dump() or dd():

foreach ($rows as $row) {
    $row = array_combine($header, $row);
    dump($row); // print the current row for debugging.
    User::create([
      'name' => $row['name'],
      ...
    ]);
  }

This will produce something like:

    array(7) {
        ["name"]=> "Claudio Magallan"
        ....
    }

    array(7) {
        ["name"]=> "Cristina Vargas"
        ....
    }

    bool(false)

So the last line before the error is false and not an array. Just filter out this element.

If only the last line is garbage: use array_pop($rows) to delete the element of $rows. Or delete line break in last line of the CSV by hand. If more lines are garbage you can use array_filter to remove non compliant lines. E.g.:

$header = array_shift($rows);
$rows = array_filter($rows, function ($row) use ($header) {
    return count($row) === count($header);
});
foreach ($rows as $row) { .. }
maxwilms
  • 1,964
  • 20
  • 23
  • Thank you so much! I was stuck in this 2 days. The array_pop function actually helps me to miss an invisible field to the final of my array and the dd function I never use it before and it helps me lot to see the function step by step. – Alan Rincón Dec 07 '18 at 17:08