Database Transactions in Laravel
JohnDivam

JohnDivam @johndivam

About: Focus on delivering high-quality solutions. #Laravel . Wye Team

Joined:
Jul 11, 2023

Database Transactions in Laravel

Publish Date: Aug 18 '23
3 1

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

Comments 1 total

  • Tony Joe Dev
    Tony Joe DevAug 22, 2023

    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
Add comment