Eloquent Many To Many Relation Between Category And

[Solved] Eloquent Many To Many Relation Between Category And | Php Frameworks Yii - Code Explorer | yomemimo.com
Question : Eloquent : many to many relation between category and posts

Answered by : poley-varro

To get all posts with related category in each post
$career = Post::whereHas('categories', function ($q) { $q->whereSlug('career'); })->wherePostType('post')->with(['categories'=>function ($q) { $q->whereSlug('career'); }])->get();
To get a category with all related posts
$carrer = Category::with('posts')->whereSlug('career')->get();
Relation in Category Model public function posts() { return $this->belongsToMany('App\Post', 'category_post', 'category_id', 'post_id'); }
Relation in Post Model public function categories() { return $this->belongsToMany('App\Category', 'category_post', 'post_id', 'category_id'); }

Source : https://laravel-tricks.com/tricks/eloquent-many-to-many-relation-between-category-and-posts | Last Update : Tue, 20 Sep 22

Answers related to eloquent many to many relation between category and posts

Code Explorer Popular Question For Php Frameworks Yii