1

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>```
5
  • 1
    Try dd($row) in your import file (before you return the model) to see what is in the array. Commented May 15, 2021 at 3:03
  • 1
    @jrcamatog Thanks for the tip! Never knew that you could dump an array like that! It returned the following array:6 [▼ "first" => "test name 1" "last" => "teast last 1" "email" => "[email protected]" "phone" => "123-123-1231" "department" => "test department" "location" => "test location" ] Commented May 15, 2021 at 3:10
  • @jrcamatog So turns out that my headers were put into the sheet in all caps... but being imported in all lowercase... I swear I tried to put the $row['FIRST'], into lowercase last night and it didnt work.. Thanks for the help <3 Commented May 15, 2021 at 3:14
  • @jrcamatog my first thought was $row was empty but actually, it had data, I realized this thanks to your comment, laravel-excel convert heading rows to lower case and replaces spaces with underscore, in my case heading was Marketplace ID and laravel-excels converted it to marketplace_id, thas why I got this error, Thanks Commented Oct 7, 2021 at 1:15
  • Question already answerd here good luck Commented Apr 23, 2022 at 18:11

2 Answers 2

4

Array keys in PHP are case sensitive.

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

Sign up to request clarification or add additional context in comments.

1 Comment

array_combine function will work with it, one array of keys and one array of values
1

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,
      ]);
}

Comments

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.