4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel リソースクラスを使ってJSONを返すときにdataというキーの中に入ってしまうことの解消方法

Last updated at Posted at 2023-09-27

概要

  • リソースクラスを使ってレスポンスで返すJSONを定義していざレスポンスを返したところ、リソースクラスのtoArrayメソッドで指定したキーがdataというキーに入ってレスポンスが返されてしまう。dataのキーを排除して1階層レスポンスのJSON情報を浅くしたい。

dataというキーはなぜ付与される?

  • dataキーはAPIに一貫性を持たせるため、laravelが自動で付与している。
  • 具体的には下記で付与されている。
    • vendor/laravel/framework/src/Illuminate/Http/Resources/Json/JsonResource.php

      vendor/laravel/framework/src/Illuminate/Http/Resources/Json/JsonResource.php
      /**
       * The "data" wrapper that should be applied.
       *
       * @var string|null
       */
      public static $wrap = 'data';
      

対応方法1 すべてのレスポンスでdataのキーを削除したい場合

  • app/Providers/AppServiceProvider.phpのbootメソッド内部に記載を行う。

    app/Providers/AppServiceProvider.php
    use Illuminate\Http\Resources\Json\JsonResource;
    
    public function boot()
    {
        JsonResource::withoutWrapping();
    }
    

対応方法2 個々のレスポンスでdataのキーを削除したい場合

  • 個々のリソースクラスに下記の内容を追記する。

    /**
     * The "data" wrapper that should be applied.
     *
     * @var string|null
     */
    public static $wrap = null;
    
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?