Site Builder Studio

SITEBUILDERSTUDIO

In Laravel you can batch queries so each only executes if they all do

In Laravel, transactions are handled using the DB facade, which provides a simple interface for beginning, committing, and rolling back transactions. The beginTransaction method is used to start a transaction, and the commit method is used to commit the transaction. If an error occurs during the transaction, the rollBack method can be used to roll back the transaction.

To use transactions in Laravel, you can wrap your database operations in a DB::transaction block. If an exception is thrown within the transaction block, the transaction will automatically be rolled back.

Big picture example;

use Illuminate\Support\Facades\DB;

try {
    DB::beginTransaction();

    // Perform database operations here
    DB::table('users')->update(['is_active' => 1]);
    DB::table('logs')->insert(['message' => 'All users were activated']);

    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    // Handle the exception
}

The cleaner way to write the same, commit and rollback will be automatic;

use Illuminate\Support\Facades\DB;

DB::transaction(function() {
    DB::table('users')->update(['is_active' => 1]);
    DB::table('logs')->insert(['message' => 'All users were activated']);
});

Now the message will only be written to log if the users are successfully updated to active. This is such a time saver and headache solver. One example use case – first create a user, then create a profile for that user, then setup a row in the billing/subscriptions table. With Laravel transactions we can avoid coding all the exception handling and if statements and make sure that either all these three things are setup or none are at all.

That’s Laravel db transactions.