PHP
Get Latest Related Record for Each Parent (Eloquent `latestOfMany`)
Learn to efficiently fetch only the single latest related record for each parent model using Laravel Eloquent's powerful `latestOfMany` relationship method.
// app/Models/User.php
class User extends Model
{
public function latestOrder()
{
return $this->hasOne(Order::class)->latestOfMany();
}
}
// app/Models/Order.php
class Order extends Model
{
protected $guarded = []; // For mass assignment example
public function user()
{
return $this->belongsTo(User::class);
}
}
// Usage Example
// Create some data for demonstration
$user1 = User::create(['name' => 'Alice']);
$user1->orders()->createMany([
['amount' => 100, 'created_at' => now()->subDays(5)],
['amount' => 150, 'created_at' => now()->subDays(2)],
]);
$user2 = User::create(['name' => 'Bob']);
$user2->orders()->createMany([
['amount' => 200, 'created_at' => now()->subDays(10)],
['amount' => 250, 'created_at' => now()->subDays(1)],
]);
// Retrieve users with their latest order
$usersWithLatestOrders = User::with('latestOrder')->get();
foreach ($usersWithLatestOrders as $user) {
if ($user->latestOrder) {
echo "User: {$user->name}, Latest Order Amount: {$user->latestOrder->amount}
";
} else {
echo "User: {$user->name}, No orders found.
";
}
}
How it works: This snippet demonstrates how to use Eloquent's `latestOfMany()` method to retrieve only the single latest (or oldest, with `oldestOfMany()`) related record for each parent model. This is a common and often complex SQL problem (e.g., "get the last order for each customer"). `latestOfMany()` simplifies this by defining a `hasOne` relationship that automatically includes the necessary subqueries to efficiently fetch only the most recent related record based on the `created_at` timestamp.