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

danimohamadnejad's avatar

how to query pivot table in eloquent before retrieving any data?

hello I am working on an ecommerce application please consider following models: Product Attribute ProductAttribute

and tables(simplest form):

products id name

attributes id name

product_attribute id product_id attribute_id value

Product and Attribute both have belongsToMany relationship and ProductAttribute is pivot model. I want to be able to get all products which have an attribute with name of "color" and value of "blue" in pivot table. actually I want to filter data without getting any data first. I dont want to query pivot table after retrieving data from productcs. I want it to happen in one query. something like:

Product::whereHas('attributes',function($q){ $q->where('name','color')->whereHas('pivot_relation',function($q2){ //and maybe here we can filter pivot table or data using $q2 or some other way???? })->with('pivot_relation'); })->get()->all();

0 likes
1 reply

Please or to participate in this conversation.