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

Full-Stack Developer
Tampa
Nu Image Medical
Senior Software Developer
Remote (US ONLY)/Kenilworth, NJ
Diversified
Senior Back-end Laravel API Developer - Immediate Contract (Full Time)
Remote
ApproveMe // Document Signing
Web Development Project Manager
Houston, TX
Swyft Filings
Experienced Laravel/VueJS Developer (Freelance)
Remote (preferably in the US)
Prosperly LLC
Senior React / Laravel Developer
Remote
The C.A.S.E. Engineering Group
Software Engineer
Boston
ButcherBox