Harsha M V
Harsha M V

Reputation: 54949

Flash Error message when Validation Fails while using FormResquest

I am using FormRequest to do my validations. I am trying to set a top-level error message via Flash to show to the user that the form submission did not succeed.

Right now I have the following UserResquest

class UserRequest extends FormRequest {
    /**
     * 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 [
            'first_name' => 'required|string|min:2|max:50',
            'last_name' => 'required|string|min:2|max:50',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:male,female'
        ];
    }

I am trying to do this in my Controller

$validator = $request->validated();

        if ($validator->fails()) {
            Session::flash('error', $validator->messages()->first());
            return redirect()->back()->withInput();
        }

But the Flash message is turning up empty. whats the best way to set the Flash Error message when using FormRequest

Am setting my Flash Message as following the View Template.

<div class="flash-message">
                @foreach (['danger', 'warning', 'success', 'info'] as $msg)
                    @if(Session::has('alert-' . $msg))
                        <p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
                    @endif
                @endforeach
            </div> <!-- end .flash-message -->

Upvotes: 2

Views: 2138

Answers (2)

N69S
N69S

Reputation: 17206

FormRequest does it automatically, you dont have to handle it in the controller.

it does so in

protected function failedValidation(Validator $validator)
{
    throw (new ValidationException($validator))
                ->errorBag($this->errorBag)
                ->redirectTo($this->getRedirectUrl());
}

You can overload the method if you want another behavior.

To get the error messages, you need to fetch it in the error bag

{{ $errors->default->first('first_name') }}

the error bag is named default by default, you can change it in your FormRequest extended class

Custom messages

To set the message per error, declare the following method in your UserRequest class

public function messages()
{
    return [
        'first_name.required' => 'A first name is required',
        'first_name.min'  => 'The first name can\'t be a single character',
        ...
    ];
}

And to know if there are errors, check the variable $errors->default in your blade then you can show the message "The Form did not save. Check below for the error and try again"

Upvotes: 4

Harsha M V
Harsha M V

Reputation: 54949

As N69S pointed out. We can set it under failedValidation as below.

/**
     * Handle a failed validation attempt.
     */
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        session()->flash('alert-danger', 'There was an error, Please try again!');
        return parent::failedValidation($validator);
    }

Upvotes: 3

Related Questions