xxkasperxx
xxkasperxx

Reputation: 11

Laravel Import Excel into DB: ErrorException Undefined array key "name"

I am trying to use the Maatwebsite\Excel package to let users import a csv or excel file and it get imported into the DB.

I am new to laravel, so I am not quite sure how to troubleshoot this issue.

I keep getting the error:

ErrorException Undefined array key "FIRST" http://127.0.0.1:8000/import-form

CSV Sample Data

FIRST,LAST,EMAIL,PHONE,DEPARTMENT,LOCATION
test name 1,teast last 1,[email protected],123-123-1231,test department,test location

Routes:


Route::post('/import-form', [ImportPatientController::class, 'importForm'])->name('import.file');

ImportPatientController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ImportPatientModel;
use Excel;
use App\Imports\PatientImport;

use App\Http\Controllers\Controller;

class ImportPatientController extends Controller
{



  public function importUploadForm()
  {
    return view('import-form');
  }

  public function importForm(Request $request)
  {
    Excel::import(new PatientImport,$request->file2);
    return "Record are imported successfully!";
  }
}

PatientImport.php (Imports Folder)

<?php

namespace App\Imports;


use App\Models\ImportPatientModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;


class PatientImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new ImportPatientModel([
            'firstName'=>$row['FIRST'],
            'lastName' => $row['LAST'],
            'email' => $row['EMAIL'],
            'phone' => $row['PHONE'],
            'department' => $row['DEPARTMENT'],
            'location' => $row['LOCATION'],
        ]);
    }
}

ImportPatientModel.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ImportPatientModel extends Model
{
    use HasFactory;

    protected $table = "imported_patients";

    protected $fillable = ['firstName', 'lastName', 'email', 'phone', 'department', 'location'];



}

import-form.blade.php

        <form action="" method="post" enctype="multipart/form-data" action="{{route('import.file')}}">
          <img class="flowhealthlogoform" src="{{ url('images/flowhealthlogo.png')}}" />
          <h1> BACKUP LIS </h1>
            <!-- CROSS Site Request Forgery Protection -->
            @csrf


            <div class="form-group">
               <label>Upload Excel Sheet</label>
               <input type="file" class="form-control {{ $errors->has('file') ? 'error' : '' }}" name="file2" id="file">

               <!-- Error -->
               @if ($errors->has('file'))
               <div class="error">
                   {{ $errors->first('file') }}
               </div>
               @endif
           </div>


            <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
        </form>```

Upvotes: 1

Views: 7320

Answers (2)

Jonatan Garces Lara
Jonatan Garces Lara

Reputation: 11

I did the same with these headers "Fecha de la encuesta","ID Único","P02. NPS Distribuidor SV","P02a. Razón NPS SV" and the model function needed to be like this. It changed all to downcase, the " " to "_" and the "." with an "a". The dd($row) helped me alot.

public function model(array $row)
{
     return new Review([
          'id_unique'  => $row['id_unico'] ?? null,
          'survey_date' => $row['fecha_de_la_encuesta'] ?? null,
          'review'    => $row['p02a_razon_nps_sv'] ?? null,
          'score'    => $row['p02_nps_distribuidor_sv'] ?? null,
      ]);
}

Upvotes: 1

Mahdi Jedari
Mahdi Jedari

Reputation: 758

Array keys in PHP are case sensitive.

I think if you change $row['FIRST'] to $row['first'] the issue will be solved!

Upvotes: 4

Related Questions