Laravel Eloquent Relationships Through Macros

Laravel Eloquent Relationships Through Macros

A new feature just merged into Laravel and included in the v5.4.8 update is the ability to define Macros for Eloquent Relationships. To better show how this feature works here is a screenshot by Jordan Pittman who created the original pull request:

Here is that same example in a copy and paste friendly version.

AppServiceProvider

use Illuminate\Database\Eloquent\Relations\HasOne;

//...

public function boot()
{
    HasMany::macro('toHasOne', function() {
        return new HasOne(
            $this->query,
            $this->parent,
            $this->foreignKey,
            $this->localKey
        );
    });
}

User Model

public function logins()
{
    return $this->hasMany(Login::class);
}

public function lastLogin()
{
    return $this->logins()->latest()->toHasOne();
}

Results

$user = App\User::find(1);
$user->logins()->first()->id; // 1
$user->logins()->count(); // 2
$logins = $user->lastLogin->id; // 2

Of course, this is just one example, and it should allow for some unique use cases in your applications.


Filed in: Laravel 5.4 / Eloquent / Macros


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
In-house Laravel Developer.
Gold Coast / Australia
MXstore
Laravel Developer
Oak Brook, IL
Tidal Commerce
Senior Backend Engineer
Santa Monica only
Saatchi Art
Senior Laravel Developer
San Francisco
Stitch Labs
Senior Software Developer
South Jordan, UT
Lendio
Full-Stack Developer
Paris, France
Wingly