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 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Full-Stack Engineer
[REMOTE: USA Only] All Other Applications Will be Rejected Immediately"
Curricula
Senior Full Stack PHP Developer
Canada
Motto Design Studio
Senior Software Engineer
Remote or Los Angeles
Coverfly
Sr. Software Engineer
Salt Lake City, UT
Clearlink
Senior Developer
Remote
ComplYant