イントロダクションIntroduction
getメソッドであれリレーションによるものであれ、Eloquentが複数のレコードをリターンする場合Illuminate\Database\Eloquent\Collectionオブジェクトが返されます。EloquentコレクションオブジェクトはLaravelのベースコレクションを継承しているので、Eloquentモデルの裏にある配列をスムーズに操作するために継承した多くのメソッドがもちろん使用できます。All multi-result sets returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends the Laravel base collection[/docs/{{version}}/collections], so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models.
全コレクションはイテレーターとしても動作し、シンプルなPHP配列のようにループで取り扱うことができます。All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
$users = App\User::where('active', 1)->get();
foreach ($users as $user) {
echo $user->name;
}
しかし、コレクションは配列よりもパワフルで直感的なインターフェイスを使ったメソッドチェーンにより、マッピングや要素の省略操作を行うことができます。例としてアクティブでないモデルを削除し、残ったユーザーのファーストネームを集めてみましょう。However, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, let's remove all inactive models and gather the first name for each remaining user:
$users = App\User::all();
$names = $users->reject(function ($user) {
return $user->active === false;
})
->map(function ($user) {
return $user->name;
});
Note: ほとんどのEloquentコレクションは新しいEloquentコレクションのインスタンスを返しますが、
pluck、keys、zip、collapse、flatten、flipメソッドはベースのコレクションインスタンスを返します。Eloquentモデルをまったく含まないコレクションを返すmap操作のような場合、自動的にベースコレクションへキャストされます。{note} While most Eloquent collection methods return a new instance of an Eloquent collection, thepluck,keys,zip,collapse,flattenandflipmethods return a base collection[/docs/{{version}}/collections] instance. Likewise, if amapoperation returns a collection that does not contain any Eloquent models, it will be automatically cast to a base collection.
使用できるメソッドAvailable Methods
全EloquentコレクションはベースのLaravelコレクションオブジェクトを拡張しており、そのためにベースコレクションクラスが提供しているパワフルなメソッドを全部継承しています。All Eloquent collections extend the base Laravel collection[/docs/{{version}}/collections#available-methods] object; therefore, they inherit all of the powerful methods provided by the base collection class.
さらに、Illuminate\Database\Eloquent\Collectionクラスは、モデルコレクションを管理するのに役立つメソッドのスーパーセットを提供しています。ほとんどのメソッドはIlluminate\Database\Eloquent\Collectionインスタンスを返しますが、いくつかのメソッドはIlluminate\Support\Collectionインスタンスを返します。In addition, the Illuminate\Database\Eloquent\Collection class provides a superset of methods to aid with managing your model collections. Most methods return Illuminate\Database\Eloquent\Collection instances; however, some methods return a base Illuminate\Support\Collection instance.
contains diff except find fresh intersect load loadMissing modelKeys makeVisible makeHidden only unique
contains($key, $operator = null, $value = null)contains($key, $operator = null, $value = null)
containsメソッドは、指定したモデルインスタンスがコレクションに含まれるかを判定します。このメソッドは主キーかモデルインスタンスを引数に取ります。The contains method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:
$users->contains(1);
$users->contains(User::find(1));
diff($items)diff($items)
diffメソッドは、指定したコレクション中に存在しないモデルをすべて返します。The diff method returns all of the models that are not present in the given collection:
use App\User;
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
except($keys)except($keys)
exceptメソッドは、指定した主キーを持たないモデルをすべて返します。The except method returns all of the models that do not have the given primary keys:
$users = $users->except([1, 2, 3]);
find($key) {#collection-method .first-collection-method}find($key) {#collection-method .first-collection-method}
findメソッドは、指定した主キーのモデルを見つけます。$keyがモデルインスタンスの場合、findはその主キーと一致するモデルを返そうとします。$keyがキーの配列の場合はwhereIn()を使用して、$keyと一致するモデルをすべて返します。The find method finds a model that has a given primary key. If $key is a model instance, find will attempt to return a model matching the primary key. If $key is an array of keys, find will return all models which match the $keys using whereIn():
$users = User::all();
$user = $users->find(1);
fresh($with = [])fresh($with = [])
freshメソッドは、コレクション中の各モデルのインスタンスをデータベースから取得します。さらに、指定されたリレーションをEagerロードします。The fresh method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded:
$users = $users->fresh();
$users = $users->fresh('comments');
intersect($items)intersect($items)
intersectメソッドは指定したコレクション中にも存在する、すべてのモデルを返します。The intersect method returns all of the models that are also present in the given collection:
use App\User;
$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());
load($relations)load($relations)
loadメソッドは指定したリレーションをコレクションの全モデルに対してEagerロードします。The load method eager loads the given relationships for all models in the collection:
$users->load('comments', 'posts');
$users->load('comments.author');
loadMissing($relations)loadMissing($relations)
loadMissingメソッドは、リレーションがまだロードされていない場合、指定したリレーションをコレクションのすべてのモデルに対してEagerロードします。The loadMissing method eager loads the given relationships for all models in the collection if the relationships are not already loaded:
$users->loadMissing('comments', 'posts');
$users->loadMissing('comments.author');
modelKeys()modelKeys()
modelKeysメソッドは、コレクションの全モデルの主キーを返します。The modelKeys method returns the primary keys for all models in the collection:
$users->modelKeys();
// [1, 2, 3, 4, 5]
makeVisible($attributes)makeVisible($attributes)
makeVisibleメソッドはコレクション中の各モデルの、通常「隠されている(hidden)」属性を可視化(Visible)にします。The makeVisible method makes attributes visible that are typically "hidden" on each model in the collection:
$users = $users->makeVisible(['address', 'phone_number']);
makeHidden($attributes)makeHidden($attributes)
makeHiddenメソッドはコレクション中の各モデルの、通常「可視化(Visible)されている」属性を可視化隠し(hidden)ます。The makeHidden method hides attributes that are typically "visible" on each model in the collection:
$users = $users->makeHidden(['address', 'phone_number']);
only($keys)only($keys)
onlyメソッドは、指定した主キーを持つモデルを全部返します。The only method returns all of the models that have the given primary keys:
$users = $users->only([1, 2, 3]);
unique($key = null, $strict = false)unique($key = null, $strict = false)
uniqueメソッドは、コレクション中のユニークなモデルをすべて返します。コレクション中の同じタイプで同じ主キーを持つモデルは削除されます。The unique method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed.
$users = $users->unique();
カスタムコレクションCustom Collections
自分で拡張したメソッドを含むカスタム「コレクション」オブジェクトを使いたい場合は、モデルのnewCollectionメソッドをオーバーライドしてください。If you need to use a custom Collection object with your own extension methods, you may override the newCollection method on your model:
<?php
namespace App;
use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 新しいEloqunetコレクションインスタンスの生成
*
* @param array $models
* @return \Illuminate\Database\Eloquent\Collection
*/
public function newCollection(array $models = [])
{
return new CustomCollection($models);
}
}
newCollectionメソッドを定義すれば、Eloquentがそのモデルの「コレクション」インスタンスを返す場合にいつでもカスタムコレクションのインスタンスを受け取れます。アプリケーションの全モデルでカスタムコレクションを使いたい場合は、全モデルが拡張しているモデルのベースクラスでnewCollectionメソッドをオーバーライドしてください。Once you have defined a newCollection method, you will receive an instance of your custom collection anytime Eloquent returns a Collection instance of that model. If you would like to use a custom collection for every model in your application, you should override the newCollection method on a base model class that is extended by all of your models.