サイトを更新しています。 数日間、レイアウトや翻訳に不具合が出ることがあります。ドキュメントは引き続きご利用いただけます。表示が崩れている場合は、後ほど再読み込みしてください。

ホーム Laravel 10.x Eloquent: コレクション

Eloquent: コレクション

10.x 2026年3月7日

#はじめに

複数のモデル結果を返すすべての Eloquent メソッドは、get メソッドやリレーションシップ経由で取得した結果を含め、Illuminate\Database\Eloquent\Collection クラスのインスタンスを返します。Eloquent コレクションオブジェクトは Laravel のベースコレクションを拡張しているため、Eloquent モデルの配列を流暢に操作するための多数のメソッドを自然に継承しています。これらの便利なメソッドについては Laravel のコレクションドキュメントを必ずご確認ください!

すべてのコレクションはイテレーターとしても機能し、単純な PHP 配列のようにループ処理ができます:

use App\Models\User;

$users = User::where('active', 1)->get();

foreach ($users as $user) {
    echo $user->name;
}

しかし前述の通り、コレクションは配列よりもはるかに強力で、直感的なインターフェイスでチェーン可能な様々な map / reduce 操作を提供します。例えば、非アクティブなモデルをすべて除外し、残ったユーザーの名前だけを取得できます:

$names = User::all()->reject(function (User $user) {
    return $user->active === false;
})->map(function (User $user) {
    return $user->name;
});

#Eloquent コレクションの変換

ほとんどの Eloquent コレクションメソッドは新しい Eloquent コレクションのインスタンスを返しますが、collapseflattenflipkeyspluckzip メソッドはベースコレクションのインスタンスを返します。同様に、map 操作が Eloquent モデルを含まないコレクションを返した場合、それはベースコレクションのインスタンスに変換されます。

#利用可能なメソッド

すべての Eloquent コレクションはベースのLaravel コレクションオブジェクトを拡張しているため、ベースコレクションクラスが提供する強力なメソッドをすべて継承しています。

さらに、Illuminate\Database\Eloquent\Collection クラスはモデルコレクションの管理を支援するメソッドのスーパーセットを提供します。ほとんどのメソッドは Illuminate\Database\Eloquent\Collection インスタンスを返しますが、modelKeys のように Illuminate\Support\Collection インスタンスを返すメソッドもあります。

<style> .collection-method-list > p { columns: 14.4em 1; -moz-columns: 14.4em 1; -webkit-columns: 14.4em 1; } .collection-method-list a { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .collection-method code { font-size: 14px; } .collection-method:not(.first-collection-method) { margin-top: 50px; } </style>

#append($attributes) {.collection-method .first-collection-method}

append メソッドは、コレクション内のすべてのモデルに対して属性を追加することを示すために使います。このメソッドは属性の配列または単一の属性を受け取ります:

$users->append('team');

$users->append(['team', 'is_admin']);

#contains($key, $operator = null, $value = null) {.collection-method}

contains メソッドは、指定したモデルインスタンスがコレクションに含まれているかどうかを判定します。主キーまたはモデルインスタンスを受け取ります:

$users->contains(1);

$users->contains(User::find(1));

#diff($items) {.collection-method}

diff メソッドは、指定したコレクションに存在しないすべてのモデルを返します:

use App\Models\User;

$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());

#except($keys) {.collection-method}

except メソッドは、指定した主キーを持たないすべてのモデルを返します:

$users = $users->except([1, 2, 3]);

#find($key) {.collection-method}

The find メソッドは、与えられたキーと一致する主キーを持つモデルを返します。$key がモデルインスタンスである場合、find は主キーと一致するモデルを返そうとします。$key がキーの配列である場合、find は与えられた配列に含まれる主キーを持つすべてのモデルを返します:

$users = User::all();

$user = $users->find(1);

#fresh($with = []) {.collection-method}

fresh メソッドは、コレクション内の各モデルの最新のインスタンスをデータベースから取得します。指定したリレーションシップもイーガーロードされます:

$users = $users->fresh();

$users = $users->fresh('comments');

#intersect($items) {.collection-method}

intersect メソッドは、指定したコレクションにも存在するすべてのモデルを返します:

use App\Models\User;

$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());

#load($relations) {.collection-method}

load メソッドは、コレクション内のすべてのモデルに対して指定したリレーションシップをイーガーロードします:

$users->load(['comments', 'posts']);

$users->load('comments.author');

$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

#loadMissing($relations) {.collection-method}

loadMissing メソッドは、指定したリレーションシップがまだロードされていない場合にのみ、コレクション内のすべてのモデルに対してイーガーロードします:

$users->loadMissing(['comments', 'posts']);

$users->loadMissing('comments.author');

$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

#modelKeys() {.collection-method}

modelKeys メソッドは、コレクション内のすべてのモデルの主キーを返します:

$users->modelKeys();

// [1, 2, 3, 4, 5]

#makeVisible($attributes) {.collection-method}

makeVisible メソッドは、通常は「非表示」になっている属性をコレクション内の各モデルで表示可能にします

$users = $users->makeVisible(['address', 'phone_number']);

#makeHidden($attributes) {.collection-method}

makeHidden メソッドは、通常は「表示されている」属性をコレクション内の各モデルで非表示にします

$users = $users->makeHidden(['address', 'phone_number']);

#only($keys) {.collection-method}

only メソッドは、指定した主キーを持つすべてのモデルを返します:

$users = $users->only([1, 2, 3]);

#setVisible($attributes) {.collection-method}

setVisible メソッドは、コレクション内の各モデルの表示属性を一時的に上書きします

$users = $users->setVisible(['id', 'name']);

#setHidden($attributes) {.collection-method}

setHidden メソッドは、コレクション内の各モデルの非表示属性を一時的に上書きします

$users = $users->setHidden(['email', 'password', 'remember_token']);

#toQuery() {.collection-method}

toQuery メソッドは、コレクションモデルの主キーに対して whereIn 制約を含む Eloquent クエリビルダーのインスタンスを返します:

use App\Models\User;

$users = User::where('status', 'VIP')->get();

$users->toQuery()->update([
    'status' => 'Administrator',
]);

#unique($key = null, $strict = false) {.collection-method}

unique メソッドは、コレクション内のユニークなモデルのみを返します。同じタイプで同じ主キーを持つモデルは重複しているため削除されます:

$users = $users->unique();

#カスタムコレクション

特定のモデルとやり取りする際にカスタムの Collection オブジェクトを使いたい場合は、モデルに newCollection メソッドを定義できます:

<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 新しい Eloquent コレクションインスタンスを作成します。
     *
     * @param  array<int, \Illuminate\Database\Eloquent\Model>  $models
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
     */
    public function newCollection(array $models = []): Collection
    {
        return new UserCollection($models);
    }
}

newCollection メソッドを定義すると、Eloquent が通常 Illuminate\Database\Eloquent\Collection インスタンスを返す場合に、カスタムコレクションのインスタンスを受け取れます。アプリケーション内のすべてのモデルでカスタムコレクションを使いたい場合は、すべてのモデルが継承するベースモデルクラスに newCollection メソッドを定義してください。