PHP
Ensuring Data Consistency with Eloquent Transactions
Discover how to use database transactions in Laravel Eloquent to group multiple database operations, ensuring they all succeed or fail together for data integrity.
use Illuminate\Support\Facades\DB;
use App\Models\Order;
use App\Models\Product;
try {
DB::transaction(function () {
// Create a new order
$order = Order::create([
'user_id' => auth()->id(),
'status' => 'pending',
'total_amount' => 0, // Will be updated later
]);
$totalAmount = 0;
$items = [
['product_id' => 1, 'quantity' => 2],
['product_id' => 2, 'quantity' => 1],
];
foreach ($items as $item) {
$product = Product::find($item['product_id']);
if (!$product || $product->stock < $item['quantity']) {
// If product not found or not enough stock, throw an exception
// This will trigger a rollback
throw new \Exception('Product ' . $item['product_id'] . ' not available or insufficient stock.');
}
// Deduct stock
$product->decrement('stock', $item['quantity']);
// Add to order items and calculate total
$order->items()->create([
'product_id' => $product->id,
'quantity' => $item['quantity'],
'price' => $product->price,
]);
$totalAmount += $product->price * $item['quantity'];
}
// Update order total
$order->update(['total_amount' => $totalAmount]);
// All operations successful, transaction commits automatically
// If any exception occurs, the transaction will be rolled back.
});
echo "Order placed successfully!";
} catch (\Exception $e) {
echo "Order failed: " . $e->getMessage();
// The transaction was automatically rolled back by DB::transaction()
}
How it works: Database transactions ensure atomicity, meaning a sequence of operations is treated as a single, indivisible unit. If all operations within the transaction succeed, changes are committed to the database. If any operation fails or an exception is thrown, all changes are rolled back, leaving the database in its original state. Laravel's `DB::transaction()` method provides a convenient way to manage this, automatically committing on success and rolling back on exceptions.