I am trying to Import Excel Data in Laravel and Insert into Database. I am using maatwebsite/excel version 3 composer package.
Error: Undefined index: customer_name
Blade file: import_excel.blade.php
<form method="post" enctype="multipart/form-data" action="{{ url('/import_excel/import') }}">
{{ csrf_field() }}
<div class="form-group">
<table class="table">
<tr>
<td width="40%" align="right"><label>Select File for Upload</label></td>
<td width="30">
<input type="file" name="select_file" />
</td>
<td width="30%" align="left">
<input type="submit" name="upload" class="btn btn-primary" value="Upload">
</td>
</tr>
<tr>
<td width="40%" align="right"></td>
<td width="30"><span class="text-muted">.xls, .xslx</span></td>
<td width="30%" align="left"></td>
</tr>
</table>
</div>
</form>
Import File: CustomerImport.php
public function model(array $row)
{
$data = [];
foreach ($row as $value)
{
$data[] = array(
'CustomerName' => $row['customer_name'],
'Gender' => $row['gender'],
'Address' => $row['address'],
'City' => $row['city'],
'PostalCode' => $row['postal_cole'],
'Country' => $row['country']
);
}
DB::table('customers')->insert($data);
}
Controller Function
public function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
Excel::import(new CustomerImport, $path);
return back()->with('success','Excel Data Imported successfully.');
}
Excel Image
Can anyone guide me please?
To use the heading row you need to implement WithHeadingRow
like this exmaple
namespace App\Imports;
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UsersImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'at' => $row['at_field'],
]);
}
}