@dgvai try this:
gets all products that have tag ids from request
$matchTags = $request->tags;
$products = Product::whereHas('tags', function($query) use ($matchTags) {
$query->whereIn('tags.id', $matchTags);
})->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am literally confused about how to proceed with the query.
I have two models:
Product - Tag are related by many-to-many relationship.
So:
// Product.php
public function tags()
{
return $this->belongsToMany(Tag::class);
}
// in Tag.php
public function products()
{
return $this->belongsToMany(Product::class);
}
Lets, query products by some tags (id), say lets find the products who has 1,2 and 3 (id) Tags.
The query should result like:
Basically what I meant:
$tags = $request->tags; // [1,2,3]
Product::where(...)->get() // where tags includes [1,2.3]
Please or to participate in this conversation.