問(wèn)題描述
我正在使用 FormRequest 來(lái)驗(yàn)證從我的 API 調(diào)用中發(fā)送的智能手機(jī)應(yīng)用程序.所以,我希望 FormRequest 在驗(yàn)證失敗時(shí)總是返回 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,F(xiàn)ormRequest的默認(rèn)行為是返回json.
I saw the following source code of Laravel framework, the default behaviour of FormRequest is return json if reqeust is Ajax or wantJson.
//IlluminateFoundationHttpFormRequest class
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return SymfonyComponentHttpFoundationResponse
*/
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);
}
我知道我可以在請(qǐng)求標(biāo)頭中添加 Accept= application/json
.FormRequest 將返回 json.但是我想提供一種更簡(jiǎn)單的方法來(lái)通過(guò)默認(rèn)支持 json 來(lái)請(qǐng)求我的 API,而無(wú)需設(shè)置任何標(biāo)頭.所以,我試圖在 IlluminateFoundationHttpFormRequest
類(lèi)中找到一些強(qiáng)制 FormRequest 響應(yīng) json 的選項(xiàng).但是我沒(méi)有找到任何默認(rèn)支持的選項(xiàng).
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 IlluminateFoundationHttpFormRequest
class. But I didn't find any options which are supported in default.
我試圖覆蓋我的應(yīng)用程序請(qǐng)求抽象類(lèi),如下所示:
I tried to overwrite my application request abstract class like followings:
<?php
namespace Laravel5CgHttpRequests;
use IlluminateFoundationHttpFormRequest;
use IlluminateHttpJsonResponse;
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 SymfonyComponentHttpFoundationResponse
*/
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);
}
}
我添加了 protected $forceJsonResponse = false;
來(lái)設(shè)置我們是否需要強(qiáng)制響應(yīng) json.并且,在從 Request 抽象類(lèi)擴(kuò)展的每個(gè) FormRequest 中.我設(shè)置了那個(gè)選項(xiàng).
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.
例如:我創(chuàng)建了一個(gè) StoreBlogPostRequest 并為此 FormRequest 設(shè)置了 $forceJsoResponse=true
并使其響應(yīng)為 json.
Eg: I made an StoreBlogPostRequest and set $forceJsoResponse=true
for this FormRequest and make it response json.
<?php
namespace Laravel5CgHttpRequests;
use Laravel5CgHttpRequestsRequest;
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:添加中間件并強(qiáng)制更改請(qǐng)求標(biāo)頭
我構(gòu)建了一個(gè)如下所示的中間件:
Solution 2: Add an Middleware and force change request header
I build a middleware like followings:
namespace Laravel5CgHttpMiddleware;
use Closure;
use SymfonyComponentHttpFoundationHeaderBag;
class AddJsonAcceptHeader
{
/**
* Add Json HTTP_ACCEPT header for an incoming request.
*
* @param IlluminateHttpRequest $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);
}
}
這是工作.但我想知道這個(gè)解決方案好嗎?在這種情況下,是否有任何 Laravel 方式可以幫助我?
It 's work. But I wonder is this solutions good? And are there any Laravel Way to help me in this situation ?
推薦答案
我很奇怪為什么在 Laravel 中很難做到這一點(diǎn).最后,根據(jù)你重寫(xiě)Request類(lèi)的想法,我想出了這個(gè).
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 AppHttpRequests;
class ApiRequest extends Request
{
public function wantsJson()
{
return true;
}
}
然后,在每個(gè)控制器中只通過(guò) AppHttpRequestsApiRequest
Then, in every controller just pass AppHttpRequestsApiRequest
公共函數(shù)索引(ApiRequest $request)
這篇關(guān)于如何在 Laravel 5.1 中強(qiáng)制 FormRequest 返回 json?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!