🔴 Laravel
Intermediate
What is Database Transactions in Laravel?
Answer
Database transactions ensure that a series of database operations either all succeed or all fail together — maintaining data integrity. In Laravel, wrap operations in a transaction: DB::transaction(function() { $user = User::create([...]); $user->wallet()->create(["balance" => 0]); }). If any exception is thrown inside the closure, Laravel automatically rolls back all changes. Manually control: DB::beginTransaction(); then DB::commit(); or DB::rollBack();. Set retry attempts for deadlocks: DB::transaction($callback, 5). Eloquent operations within a transaction are also rolled back. Always use transactions when multiple related writes must succeed or fail together — such as creating an order and updating inventory simultaneously.