【问题标题】:Setting a Flash error message with FormRequest使用 FormRequest 设置 Flash 错误消息
【发布时间】:2020-01-18 01:20:08
【问题描述】:

当表单验证失败时,我正在尝试设置并传递一条 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 -->

【问题讨论】:

  • 这意味着您没有将 Flash 类导入您的 FormRequest
  • @Flash 尝试过 - 但出现错误。 Symfony\Component\Debug\Exception\FatalThrowableError Class 'Flash' not found

标签: laravel validation laravel-6


【解决方案1】:

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

【讨论】:

  • 我试过这个,但得到了这个错误。 Symfony\Component\Debug\Exception\FatalThrowableError Class 'Flash' not found
  • 您是否介意添加所有代码并更新问题
猜你喜欢
  • 2020-05-04
  • 2016-11-24
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2021-01-07
  • 2012-06-10
相关资源
最近更新 更多