1
votes

I am attempting to set and pass a flash message, when a form validation fails. When the validation passes, I am able to set Flash message in the controller.

I have tried to override the protected failedValidation() but I get an error.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Validator;

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'
        ];
    }

    /**
     * Handle a failed validation attempt.
     */
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        Flash::error("Profile could not be saved!");
        // alert()->error('oops ... error');
        return parent::failedValidation($validator);
    } }

error:

Symfony\Component\Debug\Exception\FatalThrowableError Class 'App\Http\Requests\Flash' not found

I am setting my view in app.blade.php as follows

<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 -->
1
It means you did not Import the Flash class into your FormRequestFlash
@Flash tried it - but getting error. Symfony\Component\Debug\Exception\FatalThrowableError Class 'Flash' not foundShivam Verma

1 Answers

1
votes

you need to add use Flash; in the controller at the top after namespace declaration where you want to use the flash library methods.