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.
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;
});
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
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 return a base Illuminate\Support\Collection
instance.
contains($key, $operator = null, $value = null)
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)
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)
The except
method returns all of the models that do not have the given primary keys:
$users = $users->except([1, 2, 3]);