Home / Blog /

Throw custom ValidationException outside Requests

3 years ago

Throw custom ValidationException outside Requests

In some cases, you might want to throw a custom ValidationException. This might be required for complicated logic that does not fit in a separate Request class.

👀 669 views

To create a custom ValidationException, you can manually create one on the fly:

use Illuminate\Validation\ValidationException;

if (! $user || ! Hash::check($request->password, $user->password)) {
    throw ValidationException::withMessages([
        'email' => ['The provided credentials are incorrect.'],
    ]);
}

In the following case, if the user does not exist or the hash of the given password does not match the stored hashed password of the user, a custom ValidationException is thrown with the message: The provided credentials are incorrect. The response has the 422 status code, so the response has a similar structure as a regular Form Request validator error response.