Alan Rincón
Alan Rincón

Reputation: 3

"Undefined index: name" Laravel 5.7 Controller

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,[email protected],secret,2,60,0\r\n
    Cristina Vargas,cristyvg,[email protected],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!

Upvotes: 0

Views: 7570

Answers (1)

maxwilms
maxwilms

Reputation: 2024

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) { .. }

Upvotes: 1

Related Questions