Use Database Transactions to Keep Data Safe
Laravel Tip: Use Database Transactions to Keep Data Safe
When your code saves related records (like an order and its order items), a crash halfway through can leave the database in a broken state. Laravel’s transactions keep everything consistent — either all queries run, or none.
Old Risky Way
$order = Order::create($data);
foreach ($items as $item) {
OrderItem::create([...]);
}
// if something fails after first item → partial data!
Safer with a Transaction
use Illuminate\Support\Facades\DB;
DB::transaction(function () use ($data, $items) {
$order = Order::create($data);
foreach ($items as $item) {
OrderItem::create([
'order_id' => $order->id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
}
});
If anything inside fails, Laravel rolls it all back — no half-saved orders.
Bonus: Manual Control
DB::beginTransaction();
try {
// your DB writes
DB::commit();
} catch (\Throwable $e) {
DB::rollBack();
throw $e;
}
? Why It’s Important
Prevents corrupt or partial data
Critical for money, inventory, and sensitive workflows
Built-in & lightweight — no package needed