Database Transactions: Keep Data Consistent
Learn how to use database transactions in Laravel so multiple database changes succeed together or rollback safely.
In real applications, a single action often updates multiple tables. If one update fails and others succeed, your data becomes inconsistent. Transactions solve this by making the entire operation atomic. Common examples: - Creating an order and its order items - Charging a payment and saving an invoice - Moving funds between two accounts ## Using DB::transaction ```php use Illuminate\Support\Facades\DB; DB::transaction(function () use ($userId) { $orderId = DB::table('orders')->insertGetId([ 'user_id' => $userId, 'total' => 120, 'created_at' => now(), 'updated_at' => now(), ]); DB::table('order_items')->insert([ 'order_id' => $orderId, 'product_id' => 7, 'qty' => 2, 'price' => 60, 'created_at' => now(), 'updated_at' => now(), ]); }); ``` If anything throws an exception inside the callback, Laravel rolls back automatically. ## Graph: Transaction behavior ```mermaid flowchart TD A[Begin Transaction] --> B[Insert Order] B --> C[Insert Items] C --> D{All OK?} D -->|Yes| E[Commit] D -->|No| F[Rollback] ``` In the next tutorial, we will prevent race conditions using row locking.