Laravel - Eloquent - query many to many relationship
Example:
Table 1: posts
Table 2: categories
Pivot Table: category_post with foreign keys category_id, post_id
.....
public function categories()
{
return $this->belongsToMany('App\Categories','category_post','post_id','category_id');
}
.....
public function posts()
{
return $this->belongsToMany('App\Posts','category_post','category_id','post_id');
}
So below Eloquent will fetch 5 records where categoty_id = 11
.....
$posts = Posts::whereHas('categories', function($q) use($slug){
$q->where('id', 11); //this refers id field from categories table
})
->where('type','post')
->where('active',1)
->orderBy('post_date','desc')
->paginate(5);
just what I needed. Thanks!