問題描述
我正在使用 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的默認行為是返回json.
I saw the following source code of Laravel framework, the default behaviour of FormRequest is return json if reqeust is Ajax or wantJson.
我知道我可以在請求標頭中添加 Accept= application/json
.FormRequest 將返回 json.但是我想提供一種更簡單的方法來通過默認支持 json 來請求我的 API,而無需設置任何標頭.所以,我試圖在 IlluminateFoundationHttpFormRequest
類中找到一些強制 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 IlluminateFoundationHttpFormRequest
class. But I didn't find any options which are supported in default.
我試圖覆蓋我的應用程序請求抽象類,如下所示:
I tried to overwrite my application request abstract class like followings:
我添加了 protected $forceJsonResponse = false;
來設置我們是否需要強制響應 json.并且,在從 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.
解決方案 2:添加中間件并強制更改請求標頭
我構建了一個如下所示的中間件:
Solution 2: Add an Middleware and force change request header
I build a middleware like followings:
這是工作.但我想知道這個解決方案好嗎?在這種情況下,是否有任何 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
然后,在每個控制器中只通過 AppHttpRequestsApiRequest
Then, in every controller just pass AppHttpRequestsApiRequest
公共函數索引(ApiRequest $request)
這篇關于如何在 Laravel 5.1 中強制 FormRequest 返回 json?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!