Skip to content

Commit e7da13f

Browse files
committed
Enhance allProducts method in ProductListController to support price filtering
This commit updates the allProducts method to allow filtering of products based on minimum and maximum price parameters. It introduces a query builder that checks for price constraints on both simple products and their variations, improving the product listing functionality and user experience.
1 parent 9cd81d7 commit e7da13f

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

app/Http/Controllers/Product/ProductListController.php

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use App\Http\Resources\ProductResource;
77
use App\Models\Product;
88
use Illuminate\Http\Request;
9+
use Illuminate\Database\Eloquent\Builder;
910

1011
class ProductListController extends Controller
1112
{
@@ -16,7 +17,42 @@ public function index(){
1617
public function adsProducts($id){
1718
return ProductResource::collection(Product::inRandomOrder()->Where('subscribe_id',$id)->where('status',1)->where('is_trashed',0)->get());
1819
}
19-
public function allProducts(){
20-
return ProductResource::collection(Product::inRandomOrder()->where('status',1)->where('is_trashed',0)->paginate(6));
20+
public function allProducts(Request $request){
21+
$query = Product::inRandomOrder()
22+
->where('status', 1)
23+
->where('is_trashed', 0);
24+
if ($request->has('min_price') || $request->has('max_price')) {
25+
$query->where(function (Builder $subQuery) use ($request) {
26+
27+
// Logique pour les produits simples
28+
$subQuery->where(function ($simpleProductQuery) use ($request) {
29+
if ($request->has('min_price')) {
30+
$minPrice = floatval($request->input('min_price'));
31+
$simpleProductQuery->whereRaw('CAST(product_price AS DECIMAL(10, 2)) >= ?', [$minPrice]);
32+
}
33+
if ($request->has('max_price')) {
34+
$maxPrice = floatval($request->input('max_price'));
35+
$simpleProductQuery->whereRaw('CAST(product_price AS DECIMAL(10, 2)) <= ?', [$maxPrice]);
36+
}
37+
});
38+
39+
// Logique pour les produits variés
40+
$subQuery->orWhereHas('variations', function (Builder $variationQuery) use ($request) {
41+
if ($request->has('min_price')) {
42+
$minPrice = floatval($request->input('min_price'));
43+
$variationQuery->whereRaw('CAST(price AS DECIMAL(10, 2)) >= ?', [$minPrice]);
44+
}
45+
if ($request->has('max_price')) {
46+
$maxPrice = floatval($request->input('max_price'));
47+
$variationQuery->whereRaw('CAST(price AS DECIMAL(10, 2)) <= ?', [$maxPrice]);
48+
}
49+
});
50+
});
51+
}
52+
53+
54+
$products = $query->paginate(6);
55+
56+
return ProductResource::collection($products);
2157
}
2258
}

0 commit comments

Comments
 (0)