Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

allanjiru's avatar

Query Tags

When a user types keywords for the search filter, I want to query tags for a collection. If the keyword is "water body" the result of the filter should return collections that have both tags (water and body). My code below shows results that has either of the tags

public function searchFilter(Request $request, Collection $collection){ $terms = explode(" ", $request->input('keyword')); $collections = $collection->newQuery(); $page = (int)$request->input('page', 1); $perPage = (int)$request->input('perPage', 10); $keyword = $request->keyword;

if($request->has('keyword')){

    $collections->where(function($query) use($keyword) {
            $query->Where('name','LIKE', '%'.$keyword.'%')
            ->orWhereHas('super', function($q) use ($keyword)
            {
                $q->where('name','LIKE', '%'.$keyword.'%');
            })
            ->orWhereHas('scents', function($q) use ($keyword)
            {
                $q->where('name','LIKE', '%'.$keyword.'%');
            });
        });
}
    }
0 likes
1 reply
MohamedTammam's avatar

The code example you posted it not clear to me. So here's an example for the same case if I understood correctly.

$keywords = $request->keywords;

$posts = Post::query();

for($keywords as $k) {
	$posts->whereHas('tags', fn($q)=> $q->where('name', $k)); // Tag with a name from the keywords.
}

$posts = $posts->get();

Please or to participate in this conversation.