Database transactions
Database transactions group related local financial writes.
What it is
Database transactions group related local financial writes.
When to use it
Use a deliberate boundary for transfers and settlement updates.
Syntax
DB::transaction($callback);Example
DB::transaction(function () use ($sourceId, $destinationId, $amountCents) {
if ($amountCents <= 0 || $sourceId === $destinationId) {
throw new InvalidArgumentException("Invalid transfer");
}
$changed = DB::table("accounts")->where("id", $sourceId)
->where("balance_cents", ">=", $amountCents)
->decrement("balance_cents", $amountCents);
if ($changed !== 1) throw new RuntimeException("Debit rejected");
$credited = DB::table("accounts")->where("id", $destinationId)
->increment("balance_cents", $amountCents);
if ($credited !== 1) throw new RuntimeException("Destination missing");
});
// This focused example assumes prior authorization/currency checks.
// Add durable transfer/audit records and idempotency for a full operation.Common mistakes
Validate account scope/currency and handle duplicates; this snippet alone is not a complete payment system.