duanjing9339 2017-06-06 16:51
浏览 38
已采纳

表单请求验证返回旧输入错误

I am using Laravel's form request validation, which I find very useful, and is making my controllers a lot tidier.

My more complex validation pieces, which, if the Validator fails, should return back to the previous page, with the user's old input.

I also, sometimes, have to specify a named error bag, which again, doesn't seem to come built in as an option to the request forms.

Unfortunately, this additional error functions doesn't appear to come by default with the form requests validator.

At the moment I have:

$validator = Validator::make($request->all(), [
    'id' => 'required|numeric',
    'name' => 'required|alpha_spaces',
    'email' => 'required|email',
]);

if ($validator->fails()) {
    return back()
        ->withErrors($validator, 'aNamedErrorBag')
        ->withInput();
}

Is there a way to extract the rules into a request validator file, and return with input to the named error bag aNamedErrorBag, should the validator fail?

Many thanks

  • 写回答

1条回答 默认 最新

  • doubei8541 2017-06-06 16:58
    关注

    The FormRequest class juggles the name of the error bag as a property:

    /**
     * The key to be used for the view error bag.
     *
     * @var string
     */
    protected $errorBag = 'default';
    

    You can change this value to the errorBag that you want the errors to be sent to. Simply add it to your custom request class as a property.

    Edit

    This is what the FormRequest returns on the validation error:

    /**
     * Get the proper failed validation response for the request.
     *
     * @param  array  $errors
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function response(array $errors)
    {
        if ($this->expectsJson()) {
            return new JsonResponse($errors, 422);
        }
    
        return $this->redirector->to($this->getRedirectUrl())
                                        ->withInput($this->except($this->dontFlash))
                                        ->withErrors($errors, $this->errorBag);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大