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

2022-08-30 14:10:25

我正在使用 FormRequest 来验证从我的智能手机应用程序在 API 调用中发送的哪个。因此,我希望FormRequest在验证失败时始终返回json。

我看到了以下Laravel框架的源代码,如果reqeust是Ajax或wantJson,则FormRequest的默认行为是返回json。

//Illuminate\Foundation\Http\FormRequest class
/**
 * Get the proper failed validation response for the request.
 *
 * @param  array  $errors
 * @return \Symfony\Component\HttpFoundation\Response
 */
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);
}

我知道我可以添加请求标头。FormRequest 将返回 json。但我想提供一种更简单的方法,通过默认支持json来请求我的API,而无需设置任何标头。因此,我试图找到一些选项来强制FormRequest响应json在课堂上。但是我没有找到默认情况下支持的任何选项。Accept= application/jsonIlluminate\Foundation\Http\FormRequest

解决方案 1:覆盖请求抽象类

我试图覆盖我的应用程序请求抽象类,如下所示:

<?php

namespace Laravel5Cg\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;

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 \Symfony\Component\HttpFoundation\Response
     */
    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);
    }
}

我添加了设置,如果我们需要强制响应json或不需要。而且,在每个从请求抽象类扩展而来的FormRequest中。我设置了该选项。protected $forceJsonResponse = false;

例如:我做了一个StoreBlogPostRequest,并为此设置了FormRequest,并使其成为响应json。$forceJsoResponse=true

<?php

namespace Laravel5Cg\Http\Requests;

use Laravel5Cg\Http\Requests\Request;

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:添加中间件并强制更改请求标头

我构建了一个中间件,如下所示:

namespace Laravel5Cg\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\HeaderBag;

class AddJsonAcceptHeader
{
    /**
     * Add Json HTTP_ACCEPT header for an incoming request.
     *
     * @param  \Illuminate\Http\Request  $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方式可以帮助我?


答案 1

这让我感到困惑,为什么这在Laravel中如此困难。最后,基于您重写 Request 类的想法,我想出了这个。

app/Http/Requests/ApiRequest.php

<?php

namespace App\Http\Requests;


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

然后,在每个控制器中只需通过\App\Http\Requests\ApiRequest

public function index(ApiRequest $request)


答案 2

我知道这篇文章有点旧了,但我刚刚做了一个中间件,用“application/json”替换了请求的“Accept”标头。这将使函数在使用时返回。(这在Laravel 5.2中进行了测试,但我认为它在5.1中的工作原理相同)wantsJson()true

以下是实现方式:

  1. 创建文件app/Http/Middleware/Jsonify.php

    namespace App\Http\Middleware;
    
    use Closure;
    
    class Jsonify
    {
    
        /**
         * Change the Request headers to accept "application/json" first
         * in order to make the wantsJson() function return true
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * 
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $request->headers->set('Accept', 'application/json');
    
            return $next($request);
        }
    }
    
  2. 将中间件添加到文件表中$routeMiddlewareapp/Http/Kernel.php

    protected $routeMiddleware = [
        'auth'       => \App\Http\Middleware\Authenticate::class,
        'guest'      => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'jsonify'    => \App\Http\Middleware\Jsonify::class
    ];
    
  3. 最后,像使用任何中间件一样使用它。在我的情况下,它看起来像这样:routes.php

    Route::group(['prefix' => 'api/v1', 'middleware' => ['jsonify']], function() {
        // Routes
    });
    

推荐