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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计