Laravel Eloquent Relationships Through Macros

Tutorials

February 2nd, 2017

eloquent-macros.png

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

1use Illuminate\Database\Eloquent\Relations\HasOne;
2
3//...
4
5public function boot()
6{
7 HasMany::macro('toHasOne', function() {
8 return new HasOne(
9 $this->query,
10 $this->parent,
11 $this->foreignKey,
12 $this->localKey
13 );
14 });
15}

User Model

1public function logins()
2{
3 return $this->hasMany(Login::class);
4}
5
6public function lastLogin()
7{
8 return $this->logins()->latest()->toHasOne();
9}

Results

1$user = App\User::find(1);
2$user->logins()->first()->id; // 1
3$user->logins()->count(); // 2
4$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:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.