Search code examples
laravelmaatwebsite-excel

Undefined index: description - Uploading Excel File


Is there a way i can stop the reader from reading the excel file when any of the row data is different? When i upload an excel file, i get Undefined index: description which means description cannot be found in the file uploaded.

Is there a way i can just handle this error ?

if ($request->file('imported-file')) {
  $path = $request->file('imported-file')->getRealPath();

  $data = Excel::load($path, function($reader) {
     $reader->calculate(false);
  })->get();

  if (($request->file('imported-file')->getClientOriginalExtension()) != 'xlsx') {
    return redirect('')->with('error','File Format may not be supported');
  } else {

    if (!empty($data) && $data->count()) {
      foreach ($data->toArray() as $row) {
          if (!empty($row)) {
            $dataArray[] = [
              'name' => $row['name'],
              'description' => $row['description'],
            ];
          } 
      }

      if (!empty($dataArray)) {
         Item::insert($dataArray);

         return redirect('')->with('status','successfully added');  
      }
    }

  }
}

Solution

  • Instead of:

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

    you could use

    'description' => array_get($row, 'description'),