Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get error message from Laravel validation

Tags:

json

php

laravel

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?

like image 363
ZZZ Avatar asked Feb 15 '16 23:02

ZZZ


3 Answers

Try this:

if ($validator->fails()) {
   $error = $validator->errors()->first();
}
like image 124
rome 웃 Avatar answered Oct 20 '22 19:10

rome 웃


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 5.8 API reference though probably less useful than the source code.

like image 24
Valentine Shi Avatar answered Oct 20 '22 19:10

Valentine Shi


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)}
    });
like image 1
Jilson Thomas Avatar answered Oct 20 '22 17:10

Jilson Thomas