Eloquent: Collections

Introduction

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, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models.

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

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

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:

  1. $users = App\User::where('active', 1)->get();
  2. $names = $users->reject(function ($user) {
  3. return $user->active === false;
  4. })
  5. ->map(function ($user) {
  6. return $user->name;
  7. });

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

Available Methods

The Base Collection

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

allaverageavgchunkcollapsecontainscountdiffeacheveryexceptfilterfirstflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectisEmptykeyBykeyslastmapmaxmergeminonlypluckpopprependpullpushputrandomreducerejectreversesearchshiftshuffleslicesortsortBysortByDescsplicesumtaketoArraytoJsontransformuniquevalueswherewhereLoosezip

Custom Collections

If you need to use a custom Collection object with your own extension methods, you may override the newCollection method on your model:

  1. <?php
  2. namespace App;
  3. use App\CustomCollection;
  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 CustomCollection($models);
  16. }
  17. }

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.