Imagine transferring money from your bank account to a friend. The bank must do two things: deduct cash from your account, and add cash to your friend's account. What happens if the power cuts out right in the middle? Your friend gets nothing, but your money is gone! To prevent disasters like this, databases use something called a Transaction.

The "All or Nothing" Rule

In simple terms, a database transaction is a safety net. It wraps multiple database steps into a single rule: either every step succeeds together, or the entire operation is cancelled as if nothing ever happened. In database language, saving everything is called a commit, and undoing changes on failure is called a rollback.

Writing Safe Transactions in Laravel

Laravel makes handling transactions straightforward with DB::transaction(). You place your steps inside a closure. If anything goes wrong or throws an error, Laravel automatically triggers a rollback for you.

use Illuminate\Support\Facades\DB;

// Wrap the actions inside DB::transaction
DB::transaction(function () {
    // Step 1: Subtract $50 from the sender's account
    $sender = User::findOrFail(1);
    $sender->decrement('balance', 50);

    // Step 2: Add $50 to the receiver's account
    $receiver = User::findOrFail(2);
    $receiver->increment('balance', 50);

    // If an error happens here (e.g. database disconnects),
    // Laravel automatically cancels both steps so no money is lost!
});

Handling Deadlocks Without Panic

Sometimes two users try to update the exact same records at the very same millisecond. This traffic jam is called a deadlock. Instead of crashing, you can instruct Laravel to politely retry the transaction up to 5 times by passing a second number: DB::transaction(function () { ... }, 5);.

Quick Summary for Beginners

  • Transaction: An all-or-nothing wrapper for related database updates.
  • Rollback: An automatic undo button whenever an error occurs.
  • Best Practice: Always use DB::transaction() whenever one action depends on another.