What is Database Transactions in Laravel?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
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.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Laravel candidates.