How to display a validation message if name field is duplicate in the uploaded file?
<?php
namespace App\Imports;
use App\Models\Customer;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class CustomerImport implements ToCollection, WithHeadingRow, WithValidation
{
public $timestamps = false;
public function collection(Collection $rows)
{
foreach ($rows as $row) {
Customer::create([
'name' => $row['name'],
'address' => $row['address'],
]);
}
}
public function rules(): array
{
return [
'name' => [
'required',
'max:50',
'unique:customers,name',
],
'address' => [
'required',
'max:50',
'unique:customers,address',
]
];
}
}
My sample uploaded csv file is as follows: The name 'AAA' is duplicate. So I need to get validation error message displayed for duplicate entry in the file.
Name,Address
AAA,testaddress
AAA,testaddress1
BBB,address2
Right now I am getting Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'AAA' error.
My Controller Code is as follows:
public function uploadFile(Request $request)
{
$request->validate(
['file' => ['required', 'file', 'mimes:txt,csv']],
['file.required' => 'Please upload the file']
);
try {
Excel::import(new CustomerImport(), $request->file('file'));
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
return redirect()
->route('customers.upload')
->withErrors($failures);
}
return redirect()
->route('customers.index')
->with('success', __('customers.message_uploaded'));
}