Laravel Macros In Eloquent Relationship We can fetch one instance of hasMany relationship


Example

In our AppServiceProvider.php

public function boot()
{
  HasMany::macro('toHasOne', function() {
      return new HasOne(
          $this->query,
          $this->parent,
          $this->foreignKey,
          $this->localKey
      );
  });
}

Suppose we have shop modal and we are getting the list of products which has purchased. Suppose we have allPurchased relationship for Shop modal

public function allPurchased()
{
    return $this->hasMany(Purchased::class);
}

public function lastPurchased()
{
    return $this->allPurchased()->latest()->toHasOne();
}