Skip to content

Commit 0fcb464

Browse files
committed
Enhance allProducts method in ProductListController to support attribute filtering
This commit adds functionality to the allProducts method, allowing products to be filtered by attributes. It introduces a new query condition that processes a comma-separated string of attribute value IDs, improving the product listing experience by enabling users to view products based on their selected attributes.
1 parent d86dd23 commit 0fcb464

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

app/Http/Controllers/Product/ProductListController.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,27 @@ public function allProducts(Request $request){
8282
});
8383
}
8484

85+
if ($request->has('attributes')) {
86+
$attributesToFilter = $request->input('attributes');
87+
88+
// Check if the input is a string and handle it as a single attribute
89+
if (!is_array($attributesToFilter) && is_string($attributesToFilter)) {
90+
// Assuming a single attribute ID is passed, e.g., ?attributes=5
91+
$attributesToFilter = [$attributesToFilter => []];
92+
}
93+
94+
foreach ($attributesToFilter as $attributeId => $valueIdsString) {
95+
$valueIds = explode(',', $valueIdsString);
96+
97+
$query->whereHas('variations.attributesVariation', function (Builder $attributeQuery) use ($attributeId, $valueIds) {
98+
$attributeQuery->whereHas('attributeValue', function (Builder $attributeValueQuery) use ($attributeId, $valueIds) {
99+
$attributeValueQuery
100+
->whereIn('id', $valueIds);
101+
});
102+
});
103+
}
104+
}
105+
85106
$products = $query->paginate(6);
86107

87108
return ProductResource::collection($products);

0 commit comments

Comments
 (0)