Dynamic Eloquent Relation By Macro

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

--

--

--

Laravel developer from Iran.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
اسماعیل زارع

اسماعیل زارع

Laravel developer from Iran.

More from Medium

How to fix WordPress admin panel issue if you’ve tried everything

Laravel Best Practices You Should Follow

Laravel 7 image upload tutorial example

How is working laravel services?