Dynamic Eloquent Relation By Macro
One important thing in the modular system is dynamic variability; and most importantly, it’s a change without manipulating the kernel file.
Question :
So, suppose we have a Post model for the blog system, and then we want to add a module to add `categories` to our posts. If we do not have access to the post model file, how can we import the related relation to retrieve and save our categories?
Solution:
To put the categories relationship in our post model, we can use the macro at Laravel Eloquent Builder.
So; put this code at register method of your ServiceProvider:
// at top of your provideruse Illuminate\Database\Eloquent\Builder;
use App\Category;// at register methodBuilder::macro(‘categories’, function() {
$model = $this->getModel(); return $model->belongsToMany(Category::class);
});
At the end; for ensure that we are using relation in correct model; we should change above code like this:
// at top of your provideruse Illuminate\Database\Eloquent\Builder;
use App\Post;
use App\Category;// at register methodBuilder::macro(‘categories’, function() {
$model = $this->getModel();
if($model instanceof Post) {
return $model->belongsToMany(Category::class);
} unset(static::$macros['categories']); return $model->categories(); });