I am trying to edit code I found on a github repository of Laravel Daily https://github.com/LaravelDaily/Laravel-8-Import-CSV.
This is a system that matches the fields of the db table and a .csv document before loading the data into the database. I’m trying to add some more fields to the table, but I’m getting an error Undefined index: middle_name
because I don’t have middle_name
in the csv document.
public function parseImport(CsvImportRequest $request)
{
if ($request->has('header')) {
$headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
$data = Excel::toArray(new ContactsImport, $request->file('csv_file'))[0];
} else {
$data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
}
if (count($data) > 0) {
$csv_data = array_slice($data, 0, 2);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
// I have added this function here to get fields from my table
$contact = new Contact;
$table = $contact->getTable();
$db_field = Schema::getColumnListing($table);
return view('import_fields', [
'headings' => $headings ?? null,
'csv_data' => $csv_data,
'csv_data_file' => $csv_data_file,
'db_field' => $db_field
]);
}
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$contact = new Contact();
$table = $contact->getTable();
$db_field = Schema::getColumnListing($table);
foreach ($db_field as $index => $field) {
if ($data->csv_header) {
$contact->$field = $row[$request->fields[$field]];
} else {
$contact->$field = $row[$request->fields[$index]];
}
}
$contact->save();
}
return redirect()->route('contacts.index')->with('success', 'Import finished.');
}
My migration file is here
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name');
$table->string('email');
$table->string('phone_number')->nullable();
Also this is the structure of cvs i have
id first_name last_name email phone