Menu

📌 Transaction Kya Hoti Hai? Laravel Database Transaction Example – beginTransaction(), commit() & rollback() Explained

Laravel Database Transaction Example – beginTransaction(), commit() & rollback() Explained

Learn how to use DB::beginTransaction(), DB::commit(), and DB::rollBack() in Laravel with a simple wallet transfer example. Understand how database transactions work and why they are important for payments, balance updates, and data safety.

DB::beginTransaction();

DB::commit();

DB::rollBack();

Ya to saare database operations successfully ho jaayein,

ya agar koi ek fail ho to sab kuch wapas pehle jaisa ho jaaye.

Socho aap paise transfer kar rahe ho:

User A ke account se ₹1000 minus

User B ke account me ₹1000 add

Agar minus ho gaya aur add nahi hua To paise gayab Isliye transaction use karte hain.


❌ Without Transaction (Dangerous)

$user1 = DB::table('users')->where('id', 1)->first();

$user2 = DB::table('users')->where('id', 2)->first();

DB::table('users')->where('id', 1)->update([

    'balance' => $user1->balance - 1000

]);

// Suppose yaha error aa gaya 

DB::table('users')->where('id', 2)->update([

    'balance' => $user2->balance + 1000

]);



✅ Correct Way – Using Transaction
DB::beginTransaction();
try {
    $user1 = DB::table('users')->where('id', 1)->first();
    $user2 = DB::table('users')->where('id', 2)->first();
    DB::table('users')->where('id', 1)->update([
        'balance' => $user1->balance - 1000
    ]);
    DB::table('users')->where('id', 2)->update([
        'balance' => $user2->balance + 1000
    ]);
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
}

Flow-chart laravel

Contact