Database

Atomic Database Transactions in Laravel

Senior Editor
Sep 26, 2026
6 min read

Prevent partial data corruption during multi-table writes using DB::transaction() with automatic commit and rollback guarantees.

Why Transactions Matter

Consider creating a project and assigning default onboarding tasks. If an exception occurs after creating the project but before creating the tasks, orphaned data remains in the database.

A transaction guarantees all-or-nothing atomicity:

PHP
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($user, $projectData, $defaultTasks) {
    $project = $user->projects()->create($projectData);

    foreach ($defaultTasks as $task) {
        $project->tasks()->create($task);
    }

    return $project;
});

If any line throws a Throwable, Laravel immediately rolls back all changes made during the closure.

Topics in this article

Author

Senior Editor

Core Contributor

Related Knowledge Articles

Explore hasMany, belongsTo, belongsToMany, and polymorphic relationships in Eloquent with proper foreign key indexing and cascading deletes.
Understand how lazy loading triggers catastrophic N+1 database queries and how to prevent them using eager loading and Model::preventLazyLoading().
Learn how B-Tree, GIN, and partial indexes work in PostgreSQL to eliminate query bottlenecks and keep queries running under 5ms.