ValidationException (422)
Request data failed validation rules defined in the controller or form request.
Explanation
ValidationException is thrown when request data doesn't meet the validation rules defined using Laravel's Validator, validate() method, or Form Request classes. Laravel automatically catches this exception and returns a 422 Unprocessable Entity response with the validation errors. For web routes, it redirects back with errors. For API routes, it returns a JSON response with the error details. This is one of the most common exceptions in Laravel applications.
Common Causes
- Required field missing
- Data type mismatch
- Unique constraint violation
- String exceeds max length
- Invalid email format
Solution
Check the validation errors returned in the response or session to identify which fields failed. Review the validation rules in your controller or Form Request class. Use the errors variable in Blade templates to display validation messages. For API responses, check the JSON body for an errors object containing field-specific messages. Ensure required fields are present and data types match the expected format. Use dd(\$validator->errors()) in development to inspect all validation failures.
Code Example
// Validation in controller
public function store(Request $request)
{
$validated = $request->validate([
'email' => 'required|email|unique:users',
'name' => 'required|string|max:255',
'password' => 'required|min:8|confirmed',
]);
// If validation fails, 422 is returned automatically
return User::create($validated);
}
// Displaying errors in Blade
@if ($errors->any())
<div class="alert alert-danger">
@foreach ($errors->all() as $error)
<p>{{ $error }}</p>
@endforeach
</div>
@endif
// Getting old input after redirect
<input type="email" name="email" value="{{ old('email') }}">
Error Information
Language
php
Framework
laravel
Difficulty
Beginner
Views
344
Related Errors
PHP
Fatal Error: Uncaught Error
An unhandled Error exception was thrown that crashed the script.
PHP
Headers Already Sent
The code tries to send HTTP headers after output has already been sent to the browser.
Database
Access Denied for User
The database rejected the connection because the username or password is incorrect.
Database
Unknown Column
The SQL query references a column that doesn't exist in the specified table.