Macros In Eloquent Relationship

Other topics

We can fetch one instance of hasMany relationship

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

Contributors

Topic Id: 8998

Example Ids: 27982

This site is not affiliated with any of the contributors.