Jose
Jose

Reputation: 168

Eloquent relations belongsToMany()

I'm trying to find all the posts in various categories.

I have the Post and Category models related by belongsToMany() as follows:

Post

public function categories()
{
    return $this->belongsToMany('App\Category');
}

Category

public function posts()
{
    return $this->belongsToMany('App\Post');
}

In between there is the pivot table category_post and everything is working well with the relationships.

The problem I have is the following. When the user views a post I want to show related posts and for that I want to show the posts that belong to the same categories as the post.

If I do the following:

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->first()->posts()->get();

I recover the posts of the first category, but that post has more associated categories. And I need all the posts.

I have tried with:

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->get()->posts()->get();

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->all()->posts()->get();

And several similar things, but none works.

What would be the right way to do this, please?

Thank you.

Upvotes: 0

Views: 46

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

You can get all related posts using the whereHas() eloquent method on the Post builder.

$post = Post::where('slug',$slug)->first();

$category_ids = $post->categories->pluck('id')->all();

$related = Post::whereHas('categories', function($query) use ($category_ids) {
    $query->whereIn('id', $category_ids);
})->get();

Here, we first get the $post. Then we get all category ids for the $post.

Finally, we get all posts where it has a category with an id found in the $category_ids variable using the whereHas() builder method (followed by thewhereIn() query method).

I hope this helps.

Upvotes: 1

Related Questions