如何在Laravel 5.1中强制FormRequest返回json?
我正在使用 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);
}
我知道我可以添加请求标头。FormRequest 将返回 json。但我想提供一种更简单的方法,通过默认支持json来请求我的API,而无需设置任何标头。因此,我试图找到一些选项来强制FormRequest响应json在课堂上。但是我没有找到默认情况下支持的任何选项。Accept= application/json
Illuminate\Foundation\Http\FormRequest
解决方案 1:覆盖请求抽象类
我试图覆盖我的应用程序请求抽象类,如下所示:
<?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
*/
protected $forceJsonResponse = false;
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->forceJsonResponse || $this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
}
我添加了设置,如果我们需要强制响应json或不需要。而且,在每个从请求抽象类扩展而来的FormRequest中。我设置了该选项。protected $forceJsonResponse = false;
例如:我做了一个StoreBlogPostRequest,并为此设置了FormRequest,并使其成为响应json。$forceJsoResponse=true
<?php
namespace Laravel5Cg\Http\Requests;
use Laravel5Cg\Http\Requests\Request;
class StoreBlogPostRequest extends Request
{
/**
* Force response json type when validation fails
* @var bool
*/
protected $forceJsonResponse = true;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
}
解决方案 2:添加中间件并强制更改请求标头
我构建了一个中间件,如下所示:
namespace Laravel5Cg\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\HeaderBag;
class AddJsonAcceptHeader
{
/**
* Add Json HTTP_ACCEPT header for an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->server->set('HTTP_ACCEPT', 'application/json');
$request->headers = new HeaderBag($request->server->getHeaders());
return $next($request);
}
}
这是工作。但我想知道这个解决方案好吗?在这种情况下,是否有任何Laravel方式可以帮助我?