I tried to do excel import using Maatwebsite-3.1 and Laravel-5.8:
public function import(Request $request){
$request->validate([
'file' => 'required|max:10000|mimes:xlsx,xls',
]);
$path = $request->file('file')->getRealPath();
try{
Excel::import(new StudentsImport, $path);
} 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 back()->with('status', 'Students are added successfully!');
}
class StudentsImport implements WithMultipleSheets
{
public function sheets(): array
{
return [
new FirstStudentSheetImport()
];
}
}
class FirstStudentSheetImport implements OnEachRow, WithHeadingRow
{
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
if($rowIndex >= 200)
return; // Not more than 200 rows at a time
$row = $row->toArray();
$student_info = [
'student_id' => $tb->id,
'birthday' => $row['birthday']?? date('Y-m-d'),
'religion' => $row['religion'] ?? '',
'first_name' => $row['first_name'],
'last_name' => $row['last_name'] ?? '',
'user_id' => auth()->user()->id,
];
create(StudentInfo::class, $student_info);
}
}
When the import is successful, I got success message, but when it fails, I got error-500
How do I make the application to display the error message for failure instead of the error-500?
I was facing the same issue. On your import class you need to Implements SkipsOnError, SkipsOnFailure
your class should look like this :
With this you can catch your errors from the controller Note that you can replace
With
now all failures can be found here :
your controller should look like this.