Xml Laravel FormRequest-处理故障响应

Xml Laravel FormRequest-处理故障响应,xml,validation,laravel,laravel-5.1,Xml,Validation,Laravel,Laravel 5.1,如果我将FormRequest注入控制器方法,例如: public function createTask(CreateTaskRequest $request) { // ... } 我可以像往常一样使用rules()方法验证CreateTaskRequest中的所有数据。但是,当验证失败时,我自己如何处理响应呢?对于我们的API,有时我想返回XML响应,因此我需要某种方法来访问错误包并输出XML响应中的所有错误。以下是一些示例代码 1) 2) 下面是一些示例代码 1) 2) 在Fo

如果我将
FormRequest
注入控制器方法,例如:

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

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

以下是一些示例代码

1)

2)


下面是一些示例代码

1)

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

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

与基于请求的验证不同,使用基于控制器的(手动验证),遵循此链接我希望能解决您的问题而不是基于请求的验证,使用基于控制器的(手动验证),遵循此链接我希望能解决您的问题