
Laravel latestOfMany(): Get the Latest Related Record as a Relationship
Instead of loading an entire related collection and finding the latest record in memory, define a dedicated relationship with latestOfMany().
When a model has many related records but the application repeatedly needs only the latest one, there is no reason to load the entire collection and find that record in PHP every time.
Eloquent can express this rule as a dedicated relationship using latestOfMany().
Instead of Loading the Entire Collection
$order = $user->orders ->sortByDesc('id') ->first();public function latestOrder(): HasOne{ return $this ->hasOne(Order::class) ->latestOfMany();}In the first version, accessing $user->orders loads the related order collection before PHP sorts it and keeps only one record.
If the application specifically needs the latest order, it is better to express that directly on the model as latestOrder().
Use It Like a Normal Relationship
$user = User::query() ->with('latestOrder') ->findOrFail($userId); $order = $user->latestOrder;latestOrder can now be used like any other relationship: access it as a property, eager load it through with(), and use it in other Eloquent queries.
There is no need to load every order just to keep one result.
Reuse an Existing orders() Relationship
public function orders(): HasMany{ return $this->hasMany(Order::class);} public function latestOrder(): HasOne{ return $this ->orders() ->one() ->latestOfMany();}You do not have to repeat the relationship definition. If orders() already returns HasMany, convert it to a single-model relationship with one() and then apply latestOfMany().
What Latest Means by Default
If an increasing numeric id matches the rule you need, latestOfMany() expresses the intent well.
If "latest" in your domain is determined by a specific date, make that rule explicit instead.
Use ofMany() When Latest Means a Date
public function latestOrder(): HasOne{ return $this ->hasOne(Order::class) ->ofMany('created_at', 'max');}This relationship explicitly selects the record with the greatest created_at. It is clearer than assuming the largest id always represents the newest record according to the business rule.
If you repeatedly need only one latest model from a larger relationship, express that requirement as a relationship. latestOfMany() moves the selection to the query level instead of loading an entire collection just to keep one result.




