Your destination for complete Tech news

How to retrieve error messages in Laravel validation?

860 0
< 1 min read

You can retrieve error messages in Laravel validation using the messages() method. The messages() method returns an array of error messages for each failed validation rule. Here’s an example of how to retrieve error messages in Laravel validation:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

public function validateEmail(Request $request)
    $validator = Validator::make($request->all(), [
        'email' => 'required|email',

    if ($validator->fails()) {
        $errors = $validator->messages()->all();
        return response()->json(['errors' => $errors]);

    // If validation passes, continue with the application logic
    // ...

In this example, we’re using the Validator facade to create a validator instance for the email field. If the validator fails, we retrieve the error messages using the messages()->all() method and return them as a JSON response.

You can also retrieve the error messages for a specific field by using the messages() method with the field name as the parameter:

$errors = $validator->messages()->get('email');

In this example, we’re retrieving the error messages for the email field only.

Note that Laravel’s default validation error messages are stored in the resources/lang directory of your application. You can customize these error messages by editing the language files or by using custom error messages when defining your validation rules.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.