A transaction guarantees that a group of database operations succeeds or fails together.
Laravel:
DB::transaction(function () use ($orderData) {
$order = Order::create($orderData);
$order->items()->createMany($items);
Payment::create([
'order_id' => $order->id,
'amount' => $order->total,
]);
});
If an exception occurs, Laravel rolls back the transaction.
Scenario
Creating an order may involve:
Create order
↓
Create order items
↓
Decrease inventory
↓
Create payment record
If inventory update fails after the order was created, we don't want a half-created order.
A transaction gives us atomicity.
For critical financial/inventory workflows, I also consider locking and isolation behavior rather than assuming a transaction alone prevents race conditions.
0 comments:
Post a Comment
Thanks