Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Usual's avatar

How to get error messages from form request.

I have this form request to verify input,

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class SearchContactRequest extends Request {

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'country' => '',
                 'age' => 'integer',
        ];
    }
}

I want give some messages when user input wrong data, but how can I get those messages from session?

0 likes
11 replies
phildawson's avatar
Level 26

Add in the messages() method to that SearchContactRequest class and add any custom messages.

    public function messages()
    {
        return [
            'age.integer' => 'The age field has something entered that is not an integer',
            // ..
        ];
    }

$errors is alway available so you can do this which will output the first error for the field or empty if it passes.

{{ $errors->first('age') }}
klokand's avatar

Hi, phildawson, I was wondering how can i get or create the object of $errors and manually add new error message from other page, so when that page detects any error and redirect to the $errors display page, I can still reuse that page. cheers,

pmall's avatar

What do you try to achieve on a higher level ? Give more explanations.

klokand's avatar

like I have pageA has form and displays form validation errors list. So I was thinking if I have another pageB which has been involved with some logical deciding, I would like define one result as error and if I redirect pageB to pageA, I can reuse the errors list displaying part. I am not sure it is a good idea or not. but I guess I would like to know, how can I intervene the $errors object like add new message into it, dynamically.

pmall's avatar

I understand nothing, describe a real world use case as an example please.

phildawson's avatar

@Usual If you are talking about flashing custom error messages to the session so that they are available on the next request then it's done the easiest with withErrors.

Route::get('foo', function(){
    return redirect('bar')->withErrors([
        'baz' => 'FAIL!'
    ]);
});

Route::get('bar', function(){
    return view('bar');
});

bar.blade.php

{{ $errors->first('baz') }}

If you were dealing with the errors messagebag you could merge or add. Here it's injecting a new instance and adding a key/value to achieve the same as using an array above.

use Illuminate\Support\MessageBag;

Route::get('foo', function(MessageBag $errors){

    $errors->add('baz', 'FAIL!');

    return redirect('bar')->withErrors($errors);
});
Usual's avatar

@phildawson Yep, I got it. Now I can display my error messages in the web page under your generous help.Thanks a lot.

And once again, I read the official document carefully but found nothing about messages() function and the variable $errors.Is there some more detailed document to look up?

phildawson's avatar

@Usual Well the most recent doc updated today it's here http://laravel.com/docs/5.1/validation#validation-quickstart under Displaying The Validation Errors about the $errors variable

The methods are shown using $messages under here http://laravel.com/docs/5.1/validation#working-with-error-messages which I think isn't clear but it's the same methods and the same MessageBag instance just a different name. http://laravel.com/api/5.1/Illuminate/Support/MessageBag.html

As for the messages() method I've never found it in docs, probably deserves a pull request. If you are ever curious just follow the class it's extending back and have a look at the methods.

    /**
     * Set custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [];
    }
Usual's avatar

@phildawson Well, the messages() method is just a rewrite function in MessageBag class.

So, it is important to note that an $errors variable will always be available in all of your views on every request.

This word was found in official docs but not in the docs translated into Chinese, I got something wrong.

Many thanks.

Shahrukh4's avatar

After the updation of laravel documentation, you don't need to override the response() anymore, all you have to do is, just write your bussiness logics inside the protected failedValidation() inside your custom FormRequest class like follows,

    use Illuminate\Http\Exceptions\HttpResponseException;
    use Illuminate\Contracts\Validation\Validator;

    /**
    * [failedValidation [Overriding the event validator for custom error response]]
    * @param  Validator $validator [description]
    * @return [object][object of various validation errors]
    */
    public function failedValidation(Validator $validator) { 
         //write your bussiness logic here otherwise it will give same old JSON response
        throw new HttpResponseException(response()->json($validator->errors(), 422)); 
    }
5 likes

Please or to participate in this conversation.