Eloquent: Collections

Introduction

All Eloquent methods that return more than one model result will return instances of the Illuminate\Database\Eloquent\Collection class, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends Laravel’s base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!

All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

  1. use App\Models\User;
  2. $users = User::where('active', 1)->get();
  3. foreach ($users as $user) {
  4. echo $user->name;
  5. }

However, as previously mentioned, 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, we may remove all inactive models and then gather the first name for each remaining user:

  1. $names = User::all()->reject(function ($user) {
  2. return $user->active === false;
  3. })->map(function ($user) {
  4. return $user->name;
  5. });

Eloquent Collection Conversion

While most Eloquent collection methods return a new instance of an Eloquent collection, the collapse, flatten, flip, keys, pluck, and zip methods return a base collection instance. Likewise, if a map operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance.

Available Methods

All Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class.

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, like modelKeys, return an Illuminate\Support\Collection instance.

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

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:

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

diff($items) {.collection-method}

The diff method returns all of the models that are not present in the given collection:

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

except($keys) {.collection-method}

The except method returns all of the models that do not have the given primary keys:

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

find($key) {.collection-method}

The find method returns the model that has a primary key matching the given 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 have a primary key in the given array:

  1. $users = User::all();
  2. $user = $users->find(1);

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

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:

  1. $users = $users->fresh();
  2. $users = $users->fresh('comments');

intersect($items) {.collection-method}

The intersect method returns all of the models that are also present in the given collection:

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

load($relations) {.collection-method}

The load method eager loads the given relationships for all models in the collection:

  1. $users->load(['comments', 'posts']);
  2. $users->load('comments.author');

loadMissing($relations) {.collection-method}

The loadMissing method eager loads the given relationships for all models in the collection if the relationships are not already loaded:

  1. $users->loadMissing(['comments', 'posts']);
  2. $users->loadMissing('comments.author');

modelKeys() {.collection-method}

The modelKeys method returns the primary keys for all models in the collection:

  1. $users->modelKeys();
  2. // [1, 2, 3, 4, 5]

makeVisible($attributes) {.collection-method}

The makeVisible method makes attributes visible that are typically “hidden” on each model in the collection:

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

makeHidden($attributes) {.collection-method}

The makeHidden method hides attributes that are typically “visible” on each model in the collection:

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

only($keys) {.collection-method}

The only method returns all of the models that have the given primary keys:

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

toQuery() {.collection-method}

The toQuery method returns an Eloquent query builder instance containing a whereIn constraint on the collection model’s primary keys:

  1. use App\Models\User;
  2. $users = User::where('status', 'VIP')->get();
  3. $users->toQuery()->update([
  4. 'status' => 'Administrator',
  5. ]);

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

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:

  1. $users = $users->unique();

Custom Collections

If you would like to use a custom Collection object when interacting with a given model, you may define a newCollection method on your model:

  1. <?php
  2. namespace App\Models;
  3. use App\Support\UserCollection;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * Create a new Eloquent Collection instance.
  9. *
  10. * @param array $models
  11. * @return \Illuminate\Database\Eloquent\Collection
  12. */
  13. public function newCollection(array $models = [])
  14. {
  15. return new UserCollection($models);
  16. }
  17. }

Once you have defined a newCollection method, you will receive an instance of your custom collection anytime Eloquent would normally return an Illuminate\Database\Eloquent\Collection instance. If you would like to use a custom collection for every model in your application, you should define the newCollection method on a base model class that is extended by all of your application’s models.