Eloquent : many to many relation between category and posts

Submitted by sanjok1988 - 1 month ago

Here posts and categories have many to many relationships. the tricks are to fetch posts having a particular category attribute with categories details.

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