In Laravel, a database transaction is a way to ensure that a set of database operations either all succeed or all fail together. This is crucial when you want to maintain data consistency and integrity. If one operation fails, the transaction allows you to rollback all the previous operations so that your database doesn’t end up in an inconsistent state.
Key Concepts
- Atomicity – All queries inside a transaction are treated as a single unit. Either all succeed or none.
- Consistency – The database remains in a valid state before and after the transaction.
- Isolation – Operations inside a transaction are isolated from other concurrent operations until committed.
- Durability – Once committed, the changes are permanent.
Using Transactions in Laravel
Laravel provides the DB facade to work with transactions.
1. Basic Transaction
use Illuminate\Support\Facades\DB;
DB::beginTransaction();
try {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
DB::commit(); // Commit if all queries succeed
} catch (\Exception $e) {
DB::rollback(); // Rollback if any query fails
throw $e;
}
2. Using DB::transaction Method
Laravel provides a convenient method that automatically handles commit and rollback:
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
- If any exception occurs inside the callback, Laravel will automatically rollback.
- If all queries succeed, it commits automatically.
3. Nested Transactions
- Laravel supports nested transactions, but actual rollback behavior depends on the database driver. Laravel uses savepoints for nested transactions.
DB::transaction(function () {
// Outer transaction
DB::table('users')->update(['votes' => 1]);
DB::transaction(function () {
// Inner transaction (savepoint)
DB::table('posts')->delete();
});
});
When to Use Transactions
- Multiple related queries that must all succeed.
- Financial operations like transferring money.
- Complex CRUD operations that involve multiple tables.
- Importing or bulk updating data.
✅ Summary:
Transactions in Laravel ensure data integrity by making a group of queries atomic—either all succeed or all fail. You can use DB::beginTransaction()/DB::commit()/DB::rollback() for manual control, or DB::transaction() for a cleaner approach.
