Field Manual PHP / Laravel reference
← Laravel

Transactions

A transaction groups changes into an atomic database unit.

What it is

A transaction groups changes into an atomic database unit.

When to use it

Use when several writes must all succeed or all fail.

Syntax

DB::transaction(function () {
    // database operations
});

Example

use Illuminate\Support\Facades\DB;
DB::transaction(function () use ($order, $actor) {
    $order->status = "paid";
    $order->save();
    DB::table("audit_logs")->insert([
        "actor_id" => $actor->id, "action" => "order.paid",
        "subject_id" => $order->id, "created_at" => now(),
    ]);
});

Common mistakes

Do not swallow exceptions inside the callback; external calls do not roll back; transactions alone do not prevent all races.

Related topics

TransactionsTransactionsDatabase transactions