How to filter a model by the value of its associated model (Many-To-Many Relationship)

  • Posted on: 10 December 2019
  • By: stillfinder

Lets assume that we have 2 models Post and Tag and they are connected using Many To Many Relationship.

Post model:

class Post extends Model
    public function tags() {
        return $this->belongsToMany(Tag::class);

Tag model:

class Tag extends Model
    public function posts()
        return $this->belongsToMany(Post::class);

And we need to get all Posts with the tag 'wtf'. We can do this by dint of the next code:

$posts = Post::whereHas('tags', function ($q) use ($tag, $request) {
                $q->where('name', '=', $tag);