Laravel & Backend6 min read

Database Transactions in Laravel: Preventing Data Inconsistency

Md Shahed Alam
Md Shahed Alam
March 15, 2025
Database Transactions in Laravel: Preventing Data Inconsistency

Imagine a user places an order. Your code creates the order record, deducts from inventory, and charges the payment. What if the payment step fails after inventory was already deducted? You have a data inconsistency — inventory says it is gone, but no order was paid for.

Database transactions solve this. Either all steps succeed, or none of them do.

Basic transactions in Laravel

DB::transaction(function () use ($request) {
    $order = Order::create($request->validated());
    
    foreach ($request->items as $item) {
        $product = Product::lockForUpdate()->find($item['id']);
        $product->decrement('stock', $item['quantity']);
        $order->items()->create($item);
    }
    
    $payment = $this->paymentService->charge($order);
    $order->update(['payment_id' => $payment->id, 'status' => 'paid']);
});

If any exception is thrown inside the callback, Laravel automatically rolls back all database changes made in the transaction.

Manual transactions

Sometimes you need more control:

DB::beginTransaction();

try {
    // ... operations
    DB::commit();
} catch (Exception $e) {
    DB::rollBack();
    throw $e;
}

Deadlocks

When multiple transactions try to lock the same rows simultaneously, you can get deadlocks. Laravel's DB::transaction() automatically retries on deadlock by default. You can control how many times:

DB::transaction(function () {
    // ...
}, attempts: 5);

What belongs in a transaction?

Only database operations. Do not put email sending or API calls inside transactions. If the transaction rolls back, the email is still sent. Keep side effects outside the transaction, or dispatch them as queue jobs after commit.

LaravelBackend

Ready to build something great?

Let's talk about your project. We will give you honest advice, a clear plan, and a fair price. No pressure, no sales pitch.