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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article