Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

Maatwebsite Excel import is not displaying error message

I tried to do excel import using Maatwebsite:

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?

Thanks

0 likes
1 reply
a4ashraf's avatar

@noblemfd

you should apply try catch on here

public function onRow(Row $row)
    {   

try {
        $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);

        }catch(\Exception $e){
            
            return $e->getMessage();

        }

    }

Please or to participate in this conversation.