DEV Community

JohnDivam
JohnDivam

Posted on

Database Transactions in Laravel

In Laravel, database transactions are used to manage the integrity and consistency of the database when performing multiple database operations together. A transaction is a set of database operations that are executed as a single unit of work. If any part of the transaction fails, all the changes made within that transaction are rolled back, ensuring that the database remains in a consistent state.

DB::beginTransaction();

try {
    // Perform database operations here
    User::where('age', '>', 25)->delete();
    if(User::where('status',User::DRAFT)->first()){
      // Performing Database Operations
    }

    // Commit the transaction
    DB::commit();
} catch (\Exception $e) {
    // Something went wrong, rollback the transaction
    report($e);
    DB::rollback();
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tonyjoe profile image
Tony Joe Dev

Good, Johny.

However, I usually prefer the DB::transaction() method, that is:

DB::transaction(function () {

    User::where('age', '>', 25)->delete();
    if (User::where('status', User::DRAFT)->first()) {
      // Performing Database Operations
    }

});
Enter fullscreen mode Exit fullscreen mode