Intermediate LevelLaravel
How do DB::transaction() and automatic deadlock retry logic operate?
❓ Interview Prompt: Explain DB::transaction(), manual DB::beginTransaction() / commit() / rollBack(), and automatic SQL deadlock retries.
Database transactions guarantee atomicity (all SQL statements succeed, or all are rolled back on error).
Automatic Deadlock Retries:
'DB::transaction(function () { ... }, 5)' accepts a second integer parameter specifying how many times Laravel should automatically retry the transaction block if a SQL deadlock occurs!
Code Implementation Example
php
<?php
use IlluminateSupportFacadesDB;
// Transaction with 3 automatic deadlock retry attempts
DB::transaction(function () {
DB::table('users')->decrement('balance', 100);
DB::table('orders')->insert(['user_id' => 1, 'amount' => 100]);
}, 3);💡DB::transaction block with automatic deadlock retry count.
🎯 Interview Key Takeaway
Use DB::transaction() with a retry argument to execute atomic database operations and handle SQL deadlocks automatically.
#Transactions#Deadlocks#Database#Intermediate
Back to all Laravel Questions→