How to return custom error message from controller method validation
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
How to Return Custom Error Messages from Controller Method Validation in Laravel
In Laravel, validation plays an essential role in ensuring the data received is properly formatted and meets application requirements. By default, if a request fails validation, Laravel will return a predefined error message with the HTTP response code 422 (Unprocessable Entity). However, you might want to display specific custom messages tailored to your app's needs in certain cases. This blog post will demonstrate how you can achieve this with just a few lines of code.The Basics
To return custom error messages for validation failures, we need to follow these steps: 1. Write the rules and validate the request using Laravel's built-in validation feature. 2. When validation fails, catch the validation exceptions or errors that are generated by Laravel. 3. In our exception handler, you can set a custom message per rule if required or use the default error messages for all other cases. 4. Lastly, return the response with the appropriate status code and custom message.Implementation
Let's go through a simple example to understand how this works: Assume we want to validate an email field but instead of returning the default error message 'The email must be a valid email address', you wish to change it to something more appropriate for your app. First, add validation rules in the controller method:public function store(Request $request) {
$validate = Validator::make($request->all(), [
'email' => 'required|email|max:255'
]);
}
Now, when the request fails validation, Laravel will throw a ValidationException exception. We can handle this error in our app's Http/Kernel.php file by extending the ExceptionHandler class and overriding its render method:
public function render($request, Exception $exception) {
if ($exception instanceof ValidationException) {
return response()->json([
'errors' => [
'email' => array_merge(
[
'custom_message' => "Please enter a valid email address."
],
$exception->errors()['email']
)
]
])->setStatusCode($exception->status());
}
return parent::render($request, $exception);
}
In this example, we check if the exception is a ValidationException. If it is, we create a response array containing an 'errors' object with custom messages for specific fields. The 'email' entry will have our custom message concatenated along with any other error messages for that field. Finally, we return this response with the appropriate status code (422 in this case).