我正在使用 FormRequest来验证从我的智能手机应用程序的API调用中发送的内容.所以,我希望FormRequest在验证失败时总是返回json.
我看到了Laravel框架的以下源代码,如果reqeust是Ajax或wantJson,则FormRequest的默认行为是返回json.
//Illuminate\Foundation\Http\FormRequest class
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\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);
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以添加Accept= application/json请求标头.FormRequest将返回json.但我希望提供一种更简单的方法来通过默认支持json来请求我的API,而无需设置任何标头.所以,我试图在Illuminate\Foundation\Http\FormRequest课堂上找到一些强制FormRequest响应json的选项.但我没有找到任何默认支持的选项.
我试图覆盖我的应用程序请求抽象类,如下所示:
<?php
namespace Laravel5Cg\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
abstract class Request extends FormRequest
{
/**
* Force response json type when validation fails
* @var bool …Run Code Online (Sandbox Code Playgroud)