0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

collectionとarray & どちらを使うべきか?

Posted at

LaravelのCollectionとArrayの違い – どちらを使うべきか?

Laravelでは、データを扱う際に CollectionArray の両方を使用できます。しかし、それぞれの特徴や利点が異なります。以下で詳細を比較し、適切な場面で使い分けましょう。

1. CollectionとArrayの違い

特徴 Collection (Illuminate\Support\Collection) Array (array)
データ構造 オブジェクト (object) 配列 ([])
便利なメソッド map(), filter(), pluck(), each() など array_map(), array_filter(), array_reduce()など
イミュータブル ✅ 変更不可な場合あり ❌ 変更可能
JSONとの互換性 toJson() json_encode()
Eloquentとの互換性 User::all() で取得可 ❌ 直接は不可

2. Collectionを使うべき場合

2.1. データを柔軟に操作したいとき

Collectionは多くの便利なメソッドを提供しており、データを簡単に操作できます。

$users = collect([
    ['name' => 'A', 'age' => 25],
    ['name' => 'B', 'age' => 30],
    ['name' => 'C', 'age' => 20],
]);

// 25歳以上のユーザーを取得
$filtered = $users->filter(fn($user) => $user['age'] > 25);
dd($filtered->all()); // [['name' => 'B', 'age' => 30]]

2.2. Eloquentモデルを扱うとき

EloquentはデフォルトでCollectionを返します。

$users = User::all(); // Collectionが返る
$names = $users->pluck('name'); // 名前のリストを取得

2.3. map, reduce, filter, sort などの処理を簡単にしたいとき

$numbers = collect([1, 2, 3, 4, 5]);

$squared = $numbers->map(fn($num) => $num * $num); // 各数値を2乗
dd($squared->all()); // [1, 4, 9, 16, 25]

3. Arrayを使うべき場合

3.1. 小規模データでシンプルな処理をしたいとき

特にデータの変換などが不要な場合、Arrayで十分です。

$users = [
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
];

foreach ($users as $user) {
    echo $user['name'] . "\n";
}

3.2. パフォーマンスを重視するとき

Collectionはオブジェクトのため、Arrayの方がメモリ消費が少なく、処理が速いことがあります。

3.3. APIレスポンスとしてデータを返すとき

Collectionの toJson() も使えますが、場合によってはArrayの方が扱いやすいことがあります。

$users = User::all()->toArray(); // Collection → Arrayに変換
return response()->json($users);

4. 結論

ケース 推奨するデータ型
データをフィルタリング・マッピング・ソートしたい ✅ Collection
シンプルなデータ処理(ループのみ) ✅ Array
Eloquentのデータを扱う ✅ Collection
JSONレスポンスを返す ✅ ArrayまたはCollection (toJson())

👉 まとめ

  • データを柔軟に処理するならCollection
  • シンプルな処理やパフォーマンス重視ならArray

以上。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?