Introduction
When you retrieve multiple models with Eloquent, the results are returned as anIlluminate\Database\Eloquent\Collection.Because it extends
Illuminate\Support\Collection, all the base collection methods are available.
Available methods
Eloquent\Collection inherits every method from the base collection and adds more methods for working with models.
append / withoutAppends / setAppends
Manipulate serialization appends across the entire collection.
contains / diff / except / intersect / only
Perform containment checks, differences, intersections, exclusion, and selection based on model instances or primary keys.
find / findOrFail
Look up a model by primary key from an already-retrieved collection.
fresh
Refresh each model in the collection with the latest state from the database.
load / loadMissing
Eager-load relationships onto an already-retrieved collection after the fact.
modelKeys
Get the list of primary keys of the models in the collection.
makeVisible / makeHidden / mergeVisible / mergeHidden / setVisible / setHidden
Adjust which attributes are visible or hidden for serialization at the collection level.
partition
Split into two Eloquent\Collection instances by condition, wrapped in an outer Illuminate\Support\Collection.
toQuery
Build a whereIn query against the primary keys of the retrieved models so you can update or delete them all at once.
unique
Remove duplicate models that have the same primary key.
Converting an Eloquent collection to a base collection
collapse, flatten, flip, keys, pluck, and zip return an Illuminate\Support\Collection.Also, if the result of
map does not contain Eloquent models, it’s converted to a base collection.
Custom collections
If you want to use a model-specific collection class, the clearest option is to use the#[CollectedBy] attribute.
#[CollectedBy] attribute (recommended)
newCollection() method (alternative)
newCollection() or #[CollectedBy], your custom collection is returned wherever an Eloquent\Collection would normally be returned.If you want to apply this to all models, define
newCollection() on a common base model.
Related pages
Collections
Review the basics of
Illuminate\\Support\\Collection first.Eloquent basics
Understand the basics of models and queries before using Eloquent collections.