I have post and category many to many relationship where post and category model define correctly, I have pivot table to but no model for pivot table.
When I get one post I have the post categories to, $post->categories. I want to list all post with current post categories, for exapmle if the current post have category of A and B, I want to retrieve all posts with category of A and B. What is best and easiest way in laravel elequent for this purpose?
here my models if it help
class Post extends Model
{
public function categories(){
return $this->belongsToMany(Category::class);
}
}
class Category extends Model
{
public function posts(){
return $this->belongsToMany(Posts::class);
}
}
public function singlePost(Post $post){
$postsWithSameCategory = ???
return view('home.post',compact('post'));
}
If you want the posts with the same categories
From your example; posts with categorie A, B, A/B, A/B/C would be returned
If you want the posts with the exact same categories
From your example; Only posts with categorie A/B would be returned
To also answer your comment, you can define a scope your
Post
model