Skip to content

Commit de48110

Browse files
committed
Check cart items available quantities before checkout
1 parent f33bf03 commit de48110

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

app/Http/Controllers/CheckoutController.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,21 @@ public function checkout(Request $request)
3636
$orderItems = [];
3737
$lineItems = [];
3838
$totalPrice = 0;
39+
40+
DB::beginTransaction();
41+
42+
foreach ($products as $product) {
43+
$quantity = $cartItems[$product->id]['quantity'];
44+
if ($product->quantity !== null && $product->quantity < $quantity) {
45+
$message = match ($product->quantity) {
46+
0 => 'The product "'.$product->title.'" is out of stock',
47+
1 => 'There is only one item left for product "'.$product->title,
48+
default => 'There are only ' . $product->quantity . ' items left for product "'.$product->title,
49+
};
50+
return redirect()->back()->with('error', $message);
51+
}
52+
}
53+
3954
foreach ($products as $product) {
4055
$quantity = $cartItems[$product->id]['quantity'];
4156
$totalPrice += $product->price * $quantity;
@@ -73,7 +88,6 @@ public function checkout(Request $request)
7388
'cancel_url' => route('checkout.failure', [], true),
7489
]);
7590

76-
DB::beginTransaction();
7791
try {
7892

7993
// Create Order

0 commit comments

Comments
 (0)