0
1

More than 3 years have passed since last update.

【Laravel】Collectionのfilter後に、APIのJSONレスポンスでオブジェクトとしてレスポンスされてしまった

Posted at

はじめに

Laravelで、Collectionのfilter後に、Collection内の配列にkeyが付与されてしまい、
「APIのJSONレスポンスで配列ではなくオブジェクトとしてレスポンスされてしまう」
というケースが発生したので、メモとして残しておきます。

  • PHP 7.4.14
  • Laravel 7.27.0

結論

Collectionクラスの values() メソッドでキーをリセットする
Laravel 7.x コレクション : values()

問題になったケースのサンプル

商品テーブルから取ってきた内容に対して、filterした結果をmapでidだけにする。

Product::query()
    ->get()
    ->filter(function (Product $product) {
        return $product->amount >= 100; // 金額が100円以上の商品のみ
    })->map(function (Product $product) {
        return [
            'id' => $product->id,
        ];
    });
tinker の結果

keyが設定されている

=> Illuminate\Support\Collection {
     all: [
       2 => [
         "id" => 2,
       ],
     ],
   }

values() を付けることで解消する

Product::query()
    ->get()
    ->filter(function (Product $product) {
        return $product->amount >= 100; // 金額が100円以上の商品のみ
    })->values() // 追加
    ->map(function (Product $product) {
        return [
            'id' => $product->id,
        ];
    });
tinker の結果

keyが設定されていない

=> Illuminate\Support\Collection {
     all: [
       [
         "id" => 2,
       ],
     ],
   }
0
1
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
0
1