如何在Laravel 5.1中强制FormRequest返回json? [英] How to force FormRequest return json in Laravel 5.1?
问题描述
我正在使用 FormRequest 来验证从我的API调用中发送的内容智能手机应用程序.因此,我希望FormRequest在验证失败时始终返回json.
I'm using FormRequest to validate from which is sent in an API call from my smartphone app. So, I want FormRequest alway return json when validation fail.
我看到了以下Laravel框架的源代码,如果reqeust是Ajax或wantJson,则FormRequest的默认行为是return json.
I saw the following source code of Laravel framework, the default behaviour of FormRequest is return json if reqeust is Ajax or wantJson.
//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);
}
我知道我可以在请求标头中添加Accept= application/json
. FormRequest将返回json.但是我想提供一种更简单的方法,默认情况下通过支持json来请求我的API,而无需设置任何标头.因此,我试图找到一些选项来强制Illuminate\Foundation\Http\FormRequest
类中的FormRequest响应json.但是我没有找到默认支持的任何选项.
I knew that I can add Accept= application/json
in request header. FormRequest will return json. But I want to provide an easier way to request my API by support json in default without setting any header. So, I tried to find some options to force FormRequest response json in Illuminate\Foundation\Http\FormRequest
class. But I didn't find any options which are supported in default.
我试图覆盖我的应用程序请求抽象类,如下所示:
I tried to overwrite my application request abstract class like followings:
<?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,我在设置中添加了protected $forceJsonResponse = false;
.并且,在从Request抽象类扩展的每个FormRequest中.我设置那个选项.
I added protected $forceJsonResponse = false;
to setting if we need to force response json or not. And, in each FormRequest which is extends from Request abstract class. I set that option.
例如:我做了一个StoreBlogPostRequest并为此FormRequest设置了$forceJsoResponse=true
并使其响应json.
Eg: I made an StoreBlogPostRequest and set $forceJsoResponse=true
for this FormRequest and make it response json.
<?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:添加中间件并强制更改请求标头
我构建了如下中间件:
Solution 2: Add an Middleware and force change request header
I build a middleware like followings:
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方式可以帮助我?
It 's work. But I wonder is this solutions good? And are there any Laravel Way to help me in this situation ?
推荐答案
这让我感到困惑,为什么在Laravel中很难做到这一点.最后,基于您的想法来覆盖Request类,我想到了这个.
It boggles my mind why this is so hard to do in Laravel. In the end, based on your idea to override the Request class, I came up with this.
app/Http/Requests/ApiRequest.php
<?php
namespace App\Http\Requests;
class ApiRequest extends Request
{
public function wantsJson()
{
return true;
}
}
然后,在每个控制器中只需传递\App\Http\Requests\ApiRequest
Then, in every controller just pass \App\Http\Requests\ApiRequest
public function index(ApiRequest $request)
这篇关于如何在Laravel 5.1中强制FormRequest返回json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!