Database Transactions
Transactions ensure that a group of database operations either ALL succeed or ALL fail — there's no partial state. This is critical for operations like transferring money, creating orders with line items, or any multi-step database operation where consistency matters.
Transaction Examples
use Illuminate\Support\Facades\DB;
// Closure-based (recommended — auto commit/rollback)
DB::transaction(function () {
$order = Order::create(['user_id' => 1, 'total' => 99.99]);
$order->items()->create(['product_id' => 5, 'quantity' => 2]);
Product::where('id', 5)->decrement('stock', 2);
// If ANY of these fail, ALL are rolled back
});
// Manual transaction control
DB::beginTransaction();
try {
// ... database operations ...
DB::commit(); // Save all changes
} catch (\Exception $e) {
DB::rollBack(); // Undo all changes
throw $e;
}
// Transaction with retry on deadlock
DB::transaction(function () {
// ... operations ...
}, 3); // Retry up to 3 times on deadlockModule 4 Review
Tip
Tip
Practice Database Transactions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Transactions guarantee all-or-nothing. ACID = reliability.
Practice Task
Note
Practice Task — (1) Write a working example of Database Transactions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Database Transactions is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.