how to retrive posts where their category is same with current post in laravel?

469 Views Asked by At

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

}
1

There are 1 best solutions below

2
On BEST ANSWER

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

 public function singlePost(Post $post){

    $postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
        $query->whereIn('id', $post->categories->pluck('id'));
    })->get();
   
    return view('home.post',compact('post', 'postsWithSameCategory'));
}

If you want the posts with the exact same categories
From your example; Only posts with categorie A/B would be returned

 public function singlePost(Post $post){

    $postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
        $query->whereIn('id', $post->categories->pluck('id'));
    }, '=', $post->categories->count())->get();
   
    return view('home.post',compact('post', 'postsWithSameCategory'));
}

To also answer your comment, you can define a scope your Post model


public function scopeWhereIsRelatedWithPost($query, $post)
{
    return $query->whereHas(/** ... **/);
}

$posts = Post::whereIsRelatedWithPost($post)->get();