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:
$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::where('active', 1)->get(); $names = $users->reject(function ($user) { return $user->active === false; }) ->map(function ($user) { return $user->name; });
While most Eloquent collection methods return a new instance of an Eloquent collection, the
pluck
,keys
,zip
,collapse
,flatten
andflip
methods return a base collection instance. Likewise, if amap
operation returns a collection that does not contain any Eloquent models, it will be automatically cast to a base collection.
Please login to continue.