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

Deekshith's avatar

filter pivot table of product_categories

i have three tables like below,

products

id, name, image

categories

id,category_name,parent_id

product_categories

id,product_id,category_id

i can display category attached with product with code,

Product.php

public function Categories()
    {

        return $this->belongsToMany('\App\Models\Category'::class, 'product_categories')->withTimestamps();
    }

in controller i will get all events with categories like below,


$events = Product::with('Categories')->orderBy('id','DESC')->get();

Now i want to filter the product by category.

Ex: i want to get events which has category slug "entertainment" . How to do that dynamically? if i use whereHas it will scan full table. will it affect the performance if my table has 10000 records for each category?

0 likes
3 replies
bugsysha's avatar

Ex: i want to get events which has category slug "entertainment" . How to do that dynamically?

Product::with('Categories')->whereHas('categories', function ($query) use ($categoryName) {
  $query->where('category_name', $categoryName);
})->orderBy('id','DESC')->get();

if i use whereHas it will scan full table. will it affect the performance if my table has 10000 records for each category?

Affect performance compared to what? More complex queries are slower, but there is no faster way to do it if that is what you are asking.

Deekshith's avatar

@bugsysha thanks for the reply i have tried in another way is this fine? in Category.php i have added code,

public function products()
    {

        return $this->belongsToMany('\App\Models\Product'::class,'product_categories');
    }

in controller,

return $getEvents = Category::with('products')->where('id',$cat_id)->get();

Please or to participate in this conversation.