Laravel Tutorials

Latest and Oldest Relationship Methods in Laravel

Published
Latest and Oldest Relationship Methods in Laravel image

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 naturally
foreach ($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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article