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

Software Engineer Lead (PHP)
Remote
CivicPlus, LLC
Full-time Senior Web Developer
Detroit, MI
Wayne State University
Senior Software Engineer
Sydney, Australia
FoodByUs
Full Stack Engineer
Remote or Medford, Oregon
Empire Medical
Laravel Developer (fulltime - Dutch only)
Netherlands
Qbixx | Webservices
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Senior Quality Assurance Engineer
Remote
Bisnow Media