35

I use Laravel built-in validator and I want to get the first error message

if ($validator->fails()) {
     $error = $validator->messages()->toJson();
     .....
}

This is the result when I print error

{"name":["The name must be at least 5 characters."],"alamat":["The address must be at least 5 characters."]}

In the example above, I want to get the first error, which is "The name must be at least 5 characters.". How can I do that?

8 Answers 8

67

Try this:

if ($validator->fails()) {
   $error = $validator->errors()->first();
}
Sign up to request clarification or add additional context in comments.

Comments

17

As per 2019 Laravel 5.8 and above to get all the error messages from the validator is as easy as this:

// create the validator and make a validation here...
if ($validator->fails()) {
    $fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}

You will get the array of arrays of the fields' names and error messages. Something like this:

[
    'price'=>
        [ 
            0 => 'Price must be integer',
            1 => 'Price must be greater than 0'
        ]
    'password' => [
        [
            0 => 'Password is required'
        ]
    ]
    
]

You can use other validation messages getters that Illuminate\Support\MessageBag class provides (it is actually the object type that $validator->messages() above returns).

Message Bag Error Messages Additional Helpers

Go to your_laravel_project_dir/vendor/illuminate/support/MessageBag.php and find some useful methods like keys, has, hasAny, first, all, isEmpty etc. that you may need while checking for particular validation errors and customizing HTTP response messages.

It is easy to understand what they do by the look at the source code. Here is the Laravel 6.x API reference though probably less useful than the source code.

Comments

3

If validation fails, the withErrors method can be used to flash the error messages to the session. This is an array and this method will automatically share $errors with all views after redirection.

return redirect('register')->withErrors($validator, 'login');

The MessageBag can be accessed using the instance from the $errors variable:

{{ $errors->login->first('email') }}

Form API docs

Hope this is helpful.

Comments

3

for getting all errors, try this:

if ($validator->fails()) {
   $error = $validator->errors()->all();
}

Comments

2

In your ajax request, when you get the data, try data.name.

This will give you the error message for the name field.

$.ajax({
        url: "/your-save-url",
        type: "post",
        data: serializedData,
        success: function(data) { alert(data.name)}
    });

4 Comments

Not a solution of course. The data is not always in json format and the error field is not always name
$error = $validator->messages()->toJson(); This statement indicates you are using json response. Also, the json field contains the name attribute of the field in your form. In your case, the names are name and alamat.
How to get the first error in the Laravel backend, so it returns "The name must be at least 5 characters."
$error['name'] this will give the error for the name.
1

If you are using toastr style error displaying, this will work:

@if(session()->get('errors'))
    toastr.error("{{ session()->get('errors')->first() }}");
@endif

Comments

0

Try this

if ($validator->fails())
{
    $error = $validator->messages()->get('name');
}

Comments

-1

if you want to do it inside the controller you can:

Arr::first(Arr::flatten($validator->messages()->get('*')))

you will get the first text message

The email must be accepted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.