DEV Community

JohnDivam
JohnDivam

Posted on

2 1

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay