Martin Carlin

Laravel Excel - Throw Custom Validation Error

Reading time: Only a minute

If you are using Laravel Excel to import, you might find that you need to throw a manual exception not covered by your validation rules, here's how to do it:

Assuming we were looking for a $department model in our database based on a query that we had just executed:

if (!$department) {

    $error = ['Could not find department'];
    $failures[] = new Failure($currentRowNumber, 'department', $error, $row);

    throw new \Maatwebsite\Excel\Validators\ValidationException(\Illuminate\Validation\ValidationException::withMessages($error), $failures);
}

The exception thrown will now be consistent with the validation exception thrown by the package itself, e.g.:

try {
    $import->import($file);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {

    $failures = $e->failures();

    foreach ($failures as $failure) {
        $errors[] = [
            'row' => $failure->row(),
            'attribute' => $failure->attribute(),
            'errors' => $failure->errors(),
        ];
    }
}