Laravel theorytheory 0/50 · 0%
Database · hard

41. Database Transactions & Locking

Ensuring data consistency.

DB::transaction(function () { ... }) wraps multiple queries so they all commit or roll back together, essential for operations like transferring balances between accounts. Pessimistic locking with ->lockForUpdate() or ->sharedLock() prevents race conditions when concurrent requests modify the same rows, such as decrementing an inventory count. Deadlocks can occur if lock ordering is inconsistent across transactions, so consistent access patterns matter.

Check your understanding

  1. 1. What does ->lockForUpdate() do in a query?

  2. 2. What happens if an exception is thrown inside DB::transaction()?