Laravel FormRequest - 处理失败响应

时间:2016-01-25 23:37:25

标签: xml validation laravel laravel-5.1

如果我将FormRequest注入Controller方法,例如:

public function createTask(CreateTaskRequest $request)
{
    // ...
}

我可以像往常一样使用CreateTaskRequest方法验证rules()内的所有数据。但是,当验证失败时,我如何自己处理响应?我的API有些情况需要返回XML响应,因此我需要某种方式来访问错误包并输出XML响应中的所有错误。

2 个答案:

答案 0 :(得分:2)

FormRequest对象上,您可以覆盖response方法。验证失败时调用此方法,并传递错误数组。为了让您了解它的工作原理,内置方法如下所示:

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson()) {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

因此,对于您的情况,您希望覆盖它以返回XML响应:

public function response(array $errors)
{
    // shouldReturnXml and buildXmlResponse are just dummy function names.
    // you would need to implement their logic.

    // check conditions on whether to return xml or not
    if ($this->shouldReturnXml()) {
        // if you need xml, build it
        return $this->buildXmlResponse();
    }

    // if you don't need xml, just handle business as usual
    return parent::response($errors);
}

答案 1 :(得分:0)

以下是一些示例代码..

<强> 1)

   $file = Input::file('upload_file');
   $input = array('upload_file' => $file);

   $rules = array('upload_file' => 'image|max:3072');
   $validator = Validator::make($input, $rules);

   $errorMessageBag - $validator->getMessageBag()->toArray();

   if ( $validator->fails() ){
     return Response::json(['status' => 'fail', 'message' => $errorMessageBag]);
   }

<强> 2)

{{1}}