1

当表单验证失败时,我正在尝试设置并传递一条 Flash 消息。验证通过后,我可以在控制器中设置 Flash 消息。

我试图覆盖protected failedValidation()但我得到一个错误。

<?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);
    } }

错误:

Symfony\Component\Debug\Exception\FatalThrowableError 类 'App\Http\Requests\Flash' 未找到

我在 app.blade.php 中设置我的视图如下

<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 -->
4

1 回答 1

1

您需要use Flash;在名称空间声明后的顶部添加控制器,以便在其中使用 Flash 库方法。

于 2019-09-17T08:03:48.117 回答