如何在Laravel中一起显示验证错误和其他错误?

时间:2018-12-21 04:45:39

标签: laravel laravel-5

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

 $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”的错误一起返回到视图?

3 个答案:

答案 0 :(得分:3)

使用所有验证规则创建一个验证器实例,然后可以采用其错误并根据需要添加尽可能多的错误。类似于以下内容:

$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);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用

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

代替

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