Featured image of post Throw Laravel ValidationException Manually for API Errors

Throw Laravel ValidationException Manually for API Errors

Wrap external API errors with ValidationException::withMessages to output Laravel validation format, so the frontend displays them like regular form errors.

Scenario

When calling an external API and receiving an error response, I want to wrap the error as a ValidationException so the frontend can display it the same way as form validation errors.

Solution

1
2
3
4
5
6
7
8
9
use Illuminate\Validation\ValidationException;

try {
    // call external API
} catch (Exception $e) {
    throw ValidationException::withMessages([
        'field' => [$e->getMessage()],
    ]);
}

withMessages() accepts the same format as Validator errors — the key is the field name and the value is an array of error messages. The JSON structure the frontend receives will be identical to a regular validation failure.