pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何在 Laravel 5.1 中強制 FormRequest 返回 json?

How to force FormRequest return json in Laravel 5.1?(如何在 Laravel 5.1 中強制 FormRequest 返回 json?)
本文介紹了如何在 Laravel 5.1 中強制 FormRequest 返回 json?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在使用 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.

//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);
}

我知道我可以在請求標頭中添加 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:

<?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; 來設置我們是否需要強制響應 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.

<?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:添加中間件并強制更改請求標頭

我構建了一個如下所示的中間件:

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);
    }
}

這是工作.但我想知道這個解決方案好嗎?在這種情況下,是否有任何 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 AppHttpRequests;


class ApiRequest extends Request
{
    public function wantsJson()
    {
        return true;
    }
}

然后,在每個控制器中只通過 AppHttpRequestsApiRequest

Then, in every controller just pass AppHttpRequestsApiRequest

公共函數索引(ApiRequest $request)

這篇關于如何在 Laravel 5.1 中強制 FormRequest 返回 json?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Laravel Eloquent Union query(Laravel Eloquent Union 查詢)
Overwrite laravel 5 helper function(覆蓋 Laravel 5 輔助函數)
laravel querybuilder how to use like in wherein function(laravel querybuilder 如何在 where 函數中使用 like)
The Response content must be a string or object implementing __toString(), quot;booleanquot; given after move to psql(響應內容必須是實現 __toString()、“boolean和“boolean的字符串或對象.移動到 psql 后給出) - IT屋-程
Roles with laravel 5, how to allow only admin access to some root(Laravel 5 的角色,如何只允許管理員訪問某些根)
Laravel Auth - use md5 instead of the integrated Hash::make()(Laravel Auth - 使用 md5 而不是集成的 Hash::make())
主站蜘蛛池模板: 交联度测试仪-湿漏电流测试仪-双85恒温恒湿试验箱-常州市科迈实验仪器有限公司 | EDLC超级法拉电容器_LIC锂离子超级电容_超级电容模组_软包单体电容电池_轴向薄膜电力电容器_深圳佳名兴电容有限公司_JMX专注中高端品牌电容生产厂家 | 高压管道冲洗清洗机_液压剪叉式升降机平台厂家-林君机电 | 郑州律师咨询-郑州律师事务所_河南锦盾律师事务所 | 电主轴,车床电磨头,变频制动电机-博山鸿达特种电机 | 镀锌方管,无缝方管,伸缩套管,方矩管_山东重鑫致胜金属制品有限公司 | 成都网站建设制作_高端网站设计公司「做网站送优化推广」 | 彩超机-黑白B超机-便携兽用B超机-多普勒彩超机价格「大为彩超」厂家 | 北京工业设计公司-产品外观设计-产品设计公司-千策良品工业设计 北京翻译公司-专业合同翻译-医学标书翻译收费标准-慕迪灵 | 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 | 档案密集柜_手动密集柜_智能密集柜_内蒙古档案密集柜-盛隆柜业内蒙古密集柜直销中心 | 航空障碍灯_高中低光强航空障碍灯_民航许可认证航空警示灯厂家-东莞市天翔航天科技有限公司 | 上海皓越真空设备有限公司官网-真空炉-真空热压烧结炉-sps放电等离子烧结炉 | 正压送风机-多叶送风口-板式排烟口-德州志诺通风设备 | 有机肥设备生产制造厂家,BB掺混肥搅拌机、复合肥设备生产线,有机肥料全部加工设备多少钱,对辊挤压造粒机,有机肥造粒设备 -- 郑州程翔重工机械有限公司 | pbt头梳丝_牙刷丝_尼龙毛刷丝_PP塑料纤维合成毛丝定制厂_广州明旺 | 泥浆在线密度计厂家-防爆数字压力表-膜盒-远传压力表厂家-江苏大亚自控设备有限公司 | 聚合氯化铝价格_聚合氯化铝厂家_pac絮凝剂-唐达净水官网 | 液晶拼接屏厂家_拼接屏品牌_拼接屏价格_监控大屏—北京维康 | 恒温恒湿试验箱厂家-高低温试验箱维修价格_东莞环仪仪器_东莞环仪仪器 | SPC工作站-连杆综合检具-表盘气动量仪-内孔缺陷检测仪-杭州朗多检测仪器有限公司 | 桌上式超净工作台-水平送风超净工作台-上海康路仪器设备有限公司 | 口信网(kousing.com) - 行业资讯_行业展会_行业培训_行业资料 | 福兰德PVC地板|PVC塑胶地板|PVC运动地板|PVC商用地板-中国弹性地板系统专业解决方案领先供应商! 福建成考网-福建成人高考网 | 臭氧发生器_臭氧消毒机 - 【同林品牌 实力厂家】 | 双舌接地线-PC68数字式高阻计-ZC36|苏海百科 | 铝合金线槽_铝型材加工_空调挡水板厂家-江阴炜福金属制品有限公司 | 单锥双螺旋混合机_双螺旋锥形混合机-无锡新洋设备科技有限公司 | 自动气象站_农业气象站_超声波气象站_防爆气象站-山东万象环境科技有限公司 | 硬质合金模具_硬质合金非标定制_硬面加工「生产厂家」-西迪技术股份有限公司 | 南京PVC快速门厂家南京快速卷帘门_南京pvc快速门_世界500强企业国内供应商_南京美高门业 | 高柔性拖链电缆_卷筒电缆_耐磨耐折聚氨酯电缆-玖泰特种电缆 | 金现代信息产业股份有限公司--数字化解决方案供应商 | 京马网,京马建站,网站定制,营销型网站建设,东莞建站,东莞网站建设-首页-京马网 | 臭氧老化试验箱,高低温试验箱,恒温恒湿试验箱,防水试验设备-苏州亚诺天下仪器有限公司 | 江苏齐宝进出口贸易有限公司| 回转支承-转盘轴承-回转驱动生产厂家-洛阳隆达轴承有限公司 | 苏商学院官网 - 江苏地区唯一一家企业家自办的前瞻型、实操型商学院 | 广东风淋室_广东风淋室厂家_广东风淋室价格_广州开源_传递窗_FFU-广州开源净化科技有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 海日牌清洗剂-打造带电清洗剂、工业清洗剂等清洗剂国内一线品牌 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 |