PHP

Get Latest or Oldest Related Model with Eloquent `ofMany`

Learn how to use Laravel Eloquent's `ofMany` method to efficiently retrieve a single latest or oldest related model directly, avoiding collection loading and simplifying complex queries.

use App\Models\Order;
use App\Models\User;

// In User.php model
public function latestOrder()
{
    return $this->hasOne(Order::class)->latestOfMany();
}

public function oldestOrder()
{
    return $this->hasOne(Order::class)->oldestOfMany();
}

// Example Usage:
$users = User::with('latestOrder')->get();

foreach ($users as $user) {
    echo "User: {$user->name}
";
    if ($user->latestOrder) {
        echo "  Latest Order ID: {$user->latestOrder->id}, Total: {$user->latestOrder->total}
";
    } else {
        echo "  No orders found.
";
    }
}

$userWithOldestOrder = User::find(1)->load('oldestOrder');
if ($userWithOldestOrder && $userWithOldestOrder->oldestOrder) {
    echo "
User: {$userWithOldestOrder->name}, Oldest Order ID: {$userWithOldestOrder->oldestOrder->id}, Total: {$userWithOldestOrder->oldestOrder->total}
";
}
How it works: Often, you don't need all related models, but just the most recent or oldest one. Laravel's `ofMany` method (used via `latestOfMany()` or `oldestOfMany()`) provides a clean and efficient way to define a `hasOne` relationship that retrieves a single related model based on a "max of" or "min of" a given column (by default, `id`). This avoids loading a collection and then sorting/filtering, making your queries simpler and more performant for these common scenarios. You can also specify the column to order by and the aggregate type.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs