Laravel's latestOfMany() and oldestOfMany() methods simplify retrieving the most recent or oldest related models through Eloquent relationships. These methods transform complex queries into simple, expressive relationships.
This feature is particularly valuable when building applications that need to track history, display the most recent activities, or maintain records of first-time events.
class User extends Model{ public function latestLogin(): HasOne { return $this->hasOne(Login::class)->latestOfMany(); } public function firstPurchase(): HasOne { return $this->hasOne(Purchase::class)->oldestOfMany(); }}
Here's a practical example tracking customer interactions:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasOne; class Customer extends Model{ public function mostRecentInteraction(): HasOne { return $this->hasOne(Interaction::class) ->latestOfMany(); } public function mostValuedPurchase(): HasOne { return $this->hasOne(Purchase::class) ->ofMany('total_amount', 'max'); } public function firstSubscription(): HasOne { return $this->hasOne(Subscription::class) ->oldestOfMany('started_at'); } public function currentMembership(): HasOne { return $this->hasOne(Membership::class) ->latestOfMany() ->where('status', 'active'); }}
These relationships can be used seamlessly in your queries:
// Fetch customers with their relevant relationship data$customers = Customer::with([ 'mostRecentInteraction', 'mostValuedPurchase', 'firstSubscription', 'currentMembership'])->get(); // Access the data naturallyforeach ($customers as $customer) { dump("Last contacted: " . $customer->mostRecentInteraction->created_at); dump("Highest purchase: $" . $customer->mostValuedPurchase->total_amount);}
The latestOfMany and oldestOfMany methods turn complex sorting and filtering requirements into clean, readable relationships.