【问题标题】:How to display validation error and other errors together in Laravel?如何在 Laravel 中同时显示验证错误和其他错误?
【发布时间】:2018-12-22 00:21:37
【问题描述】:

在我的控制器中有一堆验证。在验证它们之后,我检查会话中是否存在某个元素。如果该元素不存在,那么我会发送另一个错误。我想一起显示所有验证错误和其他错误。

 $this->validate($request,[
        'other11' => 'nullable|image',
        'other12' => 'nullable|image',
        'other13' => 'nullable|image',
        'other14' => 'nullable|image',
        'other15' => 'nullable|image',
    ]);

    if(session()->get('media')['other10']==NULL)
    {
        return back()->withErrors(['other10'=>'No data in session']);
    }

目前,如果存在验证错误,则视图中不会显示有关“other10”字段的错误。有没有办法将验证错误和关于“other10”的错误一起返回到视图?

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    创建一个包含所有验证规则的验证器实例,然后您可以获取它的错误并添加任意数量的错误。它类似于以下内容:

    $validator = Validator::make($request->all(), [
        'other11' => 'nullable|image',
        'other12' => 'nullable|image',
        'other13' => 'nullable|image',
        'other14' => 'nullable|image',
        'other15' => 'nullable|image'
    ]);
    
    $errors = $validator->errors();
    
    if (session()->get('media')['other10'] == NULL) {
        $errors->add('other10', 'No data in session');
    }
    
    return back()->withErrors($errors);
    

    【讨论】:

      【解决方案2】:

      使用

      return redirect()->back()->with('error' ,'error message');
      

      而不是

      return back()->withErrors(['other10'=>'No data in session']);
      

      【讨论】:

        【解决方案3】:
        $this->validate($request,[
            'other11' => 'nullable|image',
        ]);
        

        如果有任何错误消息,验证失败,这将重定向回来。之后,在视图中打印消息,如下所示:

        @if ($errors->has('other11'))
            {{ $errors->first('email') }}
        @endif
        

        如果您想打印所有消息,这将对您有所帮助:

        @if($errors->has())
            @foreach ($errors->all() as $error)
                <div>{{ $error }}</div>
            @endforeach
        @endif
        

        最好使用来自 Laravel 的 Laravel 表单请求验证代码:

        public function rules()
        {
            return [
                'title' => 'required|unique:posts|max:255',
                'body' => 'required',
            ];
        }
        

        【讨论】:

        • 我知道如何显示错误信息。我想同时发送两个错误。例如,如果存在验证错误,则我无法显示有关 other10 字段的错误。
        • $errors = $validator->errors(); if (session()->get('media')['other10'] == NULL) { $errors->add('other10', '会话中没有数据');这将限制发送特定的错误消息,不需要返回重定向,如果任何验证失败,laravel 会自动将你重定向回来
        • 感谢“Ahmed Nour Jamal El-Din”解决了这个问题。但是为了将来,请告诉我如何在“validate”方法中编写有关“other10”字段的逻辑。
        猜你喜欢
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 2012-12-14
        • 1970-01-01
        • 2016-06-28
        • 1970-01-01
        • 2021-10-23
        相关资源
        最近更新 更多