Search code examples
laraveldatabaseeloquenttags

Laravel Posts that have specific tags and except have specific tags


i have 2 model => post and tag (many to many relation), also tag has 2 type like "trending" and "restrict"

tag model table : id - tag_type - tag_title - tag_slug

public function getTags()
{
    return $this->belongsToMany(Tag::class, 'tags_posts', 'post_id', 'tag_id');
}

i need to get posts that : when $request->trending exist return posts that have tag_type == "trending" and tag_title == $request->trending Also (this isn't conditionally and always check) except posts that have tag_type == "restrict" and tag_slug == "simple2"

i need eloquent laravel not php database , and it's important to be optimize

thanks a millions


Solution

  • Expanding on lagbox's comment, you're looking for whereHas and whereDoesntHave, passing a closure to each to do your filtering:

    Post::whereHas('tags', function($q) use($request){
        if ($request->trending) {
            $q->where('tag_type', $request->trending);
        }       
    })
    ->whereDoesntHave('tags', function($q){
        $q->where([
            'tag_type' => 'restrict',
            'tag_slug' => 'simple2'
        ]);
    });
    

    WhereHas will select only posts that have a tag with tag_type === $request->trending, WhereDoesntHave will filter out posts that have a tag with tag_type === 'restricted' and tag_slug === 'simple2'.