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

如何在 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())
主站蜘蛛池模板: 91黄在线观看 | 天天干亚洲 | 日韩成人在线免费视频 | 黄色片在线免费看 | 日韩三极 | 亚洲精品乱码久久久久久久久 | 欧美 日韩 国产 在线 | 秋霞影院一区二区 | 日韩精品久久一区 | 中文字幕 国产 | 中文字幕亚洲欧美日韩在线不卡 | 九九看片 | 日韩一区在线播放 | 亚洲一区视频 | 亚洲福利一区 | 99综合| 成人精品一区二区三区 | 亚洲精品一区国产精品 | 国产精品一二三区在线观看 | 麻豆久久久9性大片 | 欧美成人激情 | av性色全交蜜桃成熟时 | h片在线看 | 国产乱码精品1区2区3区 | 瑟瑟免费视频 | 国产精品免费在线 | 黄色在线免费观看视频 | 成人久久久 | 日本在线视频一区二区 | 欧美一页| 欧美啪啪网站 | 久久久免费 | 三级免费网 | 91人人爽 | 99热在线免费 | 视频一区二区三区中文字幕 | 日韩 国产 在线 | 久久综合狠狠综合久久 | 国产日韩在线观看一区 | 小h片免费观看久久久久 | 男女网站视频 |