← Back to all snippets
PHP

Ensuring Data Integrity with Eloquent Database Transactions

Learn how to wrap multiple database operations in an Eloquent transaction, ensuring all operations succeed or none do, maintaining data consistency.

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete(); // This operation fails

    // If any operation fails, all previous operations are rolled back.
});

// Using a try-catch block for manual transaction control:
DB::beginTransaction();
try {
    User::create(['name' => 'Alice']);
    Post::create(['title' => 'First Post']);
    
    // Simulate an error
    throw new \Exception('Something went wrong!');

    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    // Handle the error
    report($e);
}
How it works: Database transactions are crucial for maintaining data integrity when performing multiple related database operations. If any operation within the transaction fails, all previous operations within that transaction are automatically rolled back, ensuring your database remains in a consistent state. Laravel's `DB::transaction()` method provides a convenient way to achieve this, automatically handling `commit` and `rollback` based on the closure's execution. Manual `beginTransaction`, `commit`, and `rollBack` methods offer finer control for complex scenarios.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs