1
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?

【Laravel】Collectionを完全に理解する

Last updated at Posted at 2024-12-28

前提知識

LaravelでDBを扱う際の基本的な操作(Eloquent)
https://readouble.com/laravel/11.x/ja/eloquent.html

はじめに

Eloquentを取り扱うとCollectionが付き纏ってきます。
ちゃんと理解して使ってますか?

自分はCollectionの概念がよく分からず勘で使ってたので、完全に理解するべく使い方を整理してみました。

2種類のCollection

Laravelには2種類のCollectionが用意されています。

Support\Collection

Illuminate\Support\Collection
https://readouble.com/laravel/11.x/ja/collections.html#method-all

こちらが基本の認識でOK。

配列操作やデータの加工が簡単にできます。

get(), groupBy(), where()等、クエリビルダと同じ名前のメソッドがあるのがややこしいところですが、後述する基本的な取り扱いを意識すれば大丈夫かと。

Eloquent\Collection

Illuminate\Database\Eloquent\Collection
https://readouble.com/laravel/11.x/ja/eloquent-collections.html

Support\Collection を拡張しているのでどちらのメソッドも使えます。

ただ、型指定するときなどに全部こいつを使うと訳分からんことになるので、Eloquent特有の操作が必要な場合だけに留めましょう。

基本的な取り扱い

配列を取り扱う場合

public function supportCollection(): array
{
    $array = ['a' => 1, 'b' => 2, 'c' => 3];

    $collection = collect($array); // コレクション化

    // 何かしら加工(map使うとか)

    return $collection->toArray(); // 配列化して返す
}

クエリビルダを取り扱う場合

public function eloquentCollection(): array
{
    $users = User::limit(5); // クエリビルダでUserモデルを操作

    $collection = $users->get(); // コレクションとして取得

    return $collection->toArray(); // 配列として返す
}

備考

イントロダクションには次のように書いてある。

すべてのCollectionメソッドは新しいCollectionインスタンスを返します。

ただ、呼び出しもとのコレクションを更新するものもあるので注意が必要です。

  • forget()transform()など

感想

おそらく多分完全に理解できた。

調べる前は結構構えてたけど、案外時間かからなかった。

どちらかというとクエリビルダから真面目に調べたほうが良かった気がするので、そっちについても後日同じようにまとめます。

1
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
1
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?