Neo Ighodaro
← WritingDE

Laravel

Dynamic Relationships in Laravel using Eloquent Macros

Eloquent Macros are a good way to extend the functionality of your Laravel model. In this case, we will define relationships outside the model class

Laravel Eloquent macros are a great way of extending some of Laravel’s core classes. Using macros, we can extend a Laravel model to have certain relationships that have not been defined on the model class itself.

Here is an example on how to do this:

// Add to the boot() method of the AppServiceProvider
Builder::macro('warehouses', function () {
  return $this->getModel()->hasManyThrough(
    ShareholderWarehouse::class,
    City::class,
    'state_id',
    'city_id'
  );
});

Now all your models will have the warehouses relationship. You can add more logic ofcourse, but this is a good way to dynamically add model relationships.