Back to Engineering Notes
Laravel ConceptsEngineering Note

5. DB Transaction

I use database transactions to ensure data consistency and integrity when multiple operations must succeed or fail together.

🧠 Database Transaction (Laravel)

I use database transactions to ensure data consistency and integrity when multiple operations must succeed or fail together.


🎯 Simple Idea

plain text
Multiple DB operations
 ↓
Wrap in transaction
 ↓
All succeed → commit
Any fail → rollback

👉 “All or nothing”


🧩 When I Use It

creating related records (e.g., order + order items)
approval workflows (multi-step updates)
financial operations (payments, balances)
any critical operation that must stay consistent

🧱 Example

plain text
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($data) {
    $user = User::create($data['user']);

    Profile::create([
        'user_id' => $user->id,
        'bio' => $data['bio'],
    ]);
});

👉 If any query fails → everything is rolled back automatically


📌 Manual Control (Advanced)

plain text
DB::beginTransaction();

try {
    $order = Order::create([...]);

    OrderItem::create([
        'order_id' => $order->id,
    ]);

    DB::commit();
} catch (\Throwable $e) {
    DB::rollBack();
    throw $e;
}

👉 Gives more control for complex workflows


🧠 Key Behavior

plain text
Success → commit → data saved
Failure → rollback → no partial data

🧠 How I Use It in My Architecture

plain text
Controller
 ↓
Service (wrap transaction here)
 ↓
Repository
 ↓
Database

👉 I usually place transactions in the Service layer, where business logic is handled.


⚠️ Important Notes

keep transactions short and fast
avoid external API calls inside transaction
handle exceptions properly
prevent long locks on database

💬 Summary

I use database transactions to ensure that critical operations are executed safely and consistently.

plain text
Start Transaction
→ Execute multiple operations
→ Commit (success)
→ Rollback (failure)

👉 This ensures data integrity, reliability, and consistency in production systems 🚀