Skip to content

Commit 411dcfc

Browse files
committed
Increase Product quantity if order is cancelled
1 parent de48110 commit 411dcfc

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

app/Http/Controllers/Api/OrderController.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use App\Models\Api\Product;
1212
use App\Models\Order;
1313
use Illuminate\Http\Request;
14+
use Illuminate\Support\Facades\DB;
1415
use Illuminate\Support\Facades\Mail;
1516

1617
class OrderController extends Controller
@@ -40,6 +41,7 @@ public function index()
4041
public function view(Order $order)
4142
{
4243
$order->load('items.product');
44+
4345
return new OrderResource($order);
4446
}
4547

@@ -50,10 +52,27 @@ public function getStatuses()
5052

5153
public function changeStatus(Order $order, $status)
5254
{
53-
$order->status = $status;
54-
$order->save();
55+
DB::beginTransaction();
56+
try {
57+
$order->status = $status;
58+
$order->save();
59+
60+
if ($status === OrderStatus::Cancelled->value) {
61+
foreach ($order->items as $item) {
62+
$product = $item->product;
63+
if ($product && $product->quantity !== null) {
64+
$product->quantity += $item->quantity;
65+
$product->save();
66+
}
67+
}
68+
}
69+
Mail::to($order->user)->send(new OrderUpdateEmail($order));
70+
} catch (\Exception $e) {
71+
DB::rollBack();
72+
throw $e;
73+
}
5574

56-
Mail::to($order->user)->send(new OrderUpdateEmail($order));
75+
DB::commit();
5776

5877
return response('', 200);
5978
}

0 commit comments

Comments
 (0)