I am trying to validate data from multiple sheets in laravel using maatwebsite/excel package. Here's my controller code.
try {
$import = new ImportMark($data);
Excel::import($import, $request->file('xls')->store('files'));
return redirect()->route('marks.index')->with('success', __('marks.batch_success', ['count'=>'']));
} 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.
}
return redirect()->back()->withInput()->with('xls_errors', $failures);
} catch(\Exception $ex){
return redirect()->back()->withInput()->with('failure', $ex->getMessage());
}
So far, I have acheived the following.

However, I am unable to get the sheetname in which the validation has failed. My Sheet looks like this.

I am trying to show the sheetName (1031-Comp. Mathematics) in which the validation failed. Here's my ImportMark Class
class ImportMark implements WithMultipleSheets, WithEvents{
protected $data;
protected $no_of_sheets;
protected $totalRows;
public $sheetNames;
public $sheetData;
public function __construct($data){
$this->data = $data;
$this->sheetData = array_fill(0, 4, new ImportSubjectWiseSheet($this->data));
}
public function sheets(): array{
return $this->sheetData;
}
public function registerEvents(): array
{
return [
BeforeImport::class => function (BeforeImport $event) {
$this->totalRows = $event->getReader()->getTotalRows();
},
BeforeSheet::class => function(BeforeSheet $event) {
$this->sheetNames[] = $event->getSheet()->getTitle();
}
];
}
public function getSheetNames() {
return $this->sheetNames;
}
}
ImportMarkclass you could add a property to store the current sheet call being processed:ValidationExceptionand include the sheet name in the error messages:Now, when you catch a
ValidationException, you can use$import->getCurrentSheetName()to get the sheet call in which the validation failed