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.