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


In our AppServiceProvider.php

public function boot()
  HasMany::macro('toHasOne', function() {
      return new HasOne(

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();