Not getting all errors of row in a sequence in Laravel Excel
Hello I am using Laravel Excel to import data into database, all the things working fine but I am getting error . when something happens unexpected and it returns like this. I want to group the error all errors for each row.
There was an error on row 2. The gr field is required.
There was an error on row 3. The gr field is required.
There was an error on row 2. The place_of_birth field is required.
There was an error on row 3. The place_of_birth field is required.
But I need this in a sequence according to rows not columns, like:
There was an error on row 2. The gr field is required.
There was an error on row 2. The place_of_birth field is required.
There was an error on row 3. The gr field is required.
There was an error on row 3. The place_of_birth field is required.
How can I modify my methods:
public function rules(): array
{
return [
'*.temporary_gr' => 'required|unique:admissions,temporary_gr|string|min:1,max:10',
'*.place_of_birth' => 'required|alpha|max:30',
]
}
public function collection(Collection $rows)
{
foreach($rows as $row) {
$admisssion = new Admission();
$admisssion->gr = $row["gr"];
$admisssion->dob = $row["dob"];
$admisssion->save();
}
}
Laravel Excel docs shows how to customize handling validation errors:
try {
$import->import('import-users.xlsx');
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
}
Code above is copied straight from the docs, but you can manipulate the $e->failures() response to reorder its items before sending it back to the browser.