久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何在 Laravel 5.1 中強(qiáng)制 FormRequest 返回 json?

How to force FormRequest return json in Laravel 5.1?(如何在 Laravel 5.1 中強(qiáng)制 FormRequest 返回 json?)
本文介紹了如何在 Laravel 5.1 中強(qiáng)制 FormRequest 返回 json?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問(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)!

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

相關(guān)文檔推薦

Laravel Eloquent Union query(Laravel Eloquent Union 查詢)
Overwrite laravel 5 helper function(覆蓋 Laravel 5 輔助函數(shù))
laravel querybuilder how to use like in wherein function(laravel querybuilder 如何在 where 函數(shù)中使用 like)
The Response content must be a string or object implementing __toString(), quot;booleanquot; given after move to psql(響應(yīng)內(nèi)容必須是實(shí)現(xiàn) __toString()、“boolean和“boolean的字符串或?qū)ο?移動(dòng)到 psql 后給出) - IT屋-程
Roles with laravel 5, how to allow only admin access to some root(Laravel 5 的角色,如何只允許管理員訪問(wèn)某些根)
Laravel Auth - use md5 instead of the integrated Hash::make()(Laravel Auth - 使用 md5 而不是集成的 Hash::make())
主站蜘蛛池模板: 久视频在线 | 天天人人精品 | 亚洲精品一区二区三区在线观看 | 国产精品久久久久久影院8一贰佰 | 日日操夜夜操视频 | 婷婷色国产偷v国产偷v小说 | 天堂在线一区 | 色性av| 911精品国产 | 99精品一区二区 | 日韩在线精品视频 | 激情欧美一区二区三区中文字幕 | 亚洲一区二区成人 | 毛片在线视频 | 国产小视频在线 | 久久这里只有精品首页 | 一区二区三区视频免费看 | 久久久激情 | a免费视频 | 国产在线精品一区二区 | 精品久久久久久亚洲精品 | 亚洲免费视频网址 | 日韩高清国产一区在线 | 涩爱av一区二区三区 | 欧美精品在线免费观看 | 国产在线视频一区二区 | 国产精品视频一 | 久久专区| 亚洲成人精品久久久 | 国产精品免费av | 久久久久久亚洲欧洲 | 91视频日本| 成人午夜影院 | caoporn国产精品免费公开 | 一区二区三区免费 | 97精品久久 | 免费艹逼视频 | 精品久久久久久国产 | 九九热精 | 中文字幕1区 | 日本三级全黄三级a |