Laravel Validation Error messages


Example

Customizing error messages

The /resources/lang/[lang]/validation.php files contain the error messages to be used by the validator. You can edit them as needed.

Most of them have placeholders which will be automatically replaced when generating the error message.

For example, in 'required' => 'The :attribute field is required.', the :attribute placeholder will be replaced by the field name (alternatively, you can also customize the display value of each field in the attributes array in the same file).

Example

message configuration:

'required' => 'Please inform your :attribute.',
//...
'attributes => [
    'email' => 'E-Mail address'
]

rules:

`email' => `required`

resulting error message:

"Please inform your E-Mail address."


Customising error messages within a Request class

The Request class has access to a messages() method which should return an array, this can be used to override messages without having to go into the lang files. For example if we have a custom file_exists validation you can messages like below.

class SampleRequest extends Request {

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'image' =>  'required|file_exists'
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function messages()
    {
        return [
            'image.file_exists' =>  'That file no longer exists or is invalid'
        ];
    }

}

Displaying error messages

The validation errors are flashed to the session, and are also available in the $errors variable, which is automatically shared to all views.

Example of displaying the errors in a Blade view:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif