Sunday, 26 February 2017

Importance of Database Transaction in Laravel

Database Transaction comes into the picture when we have Sequential Operation with DB(mainly Update and Delete). A lot can happen in between transactions. So we should have system in place for the Rollback in case something bad happens.

Here is a simple code snippet for Manual use of Transaction.

DB::beginTransaction();
try {
    $user->save();
    $company->save();
    $department->save();

    //Commit to DB if all is well
    DB::commit();
} catch (Exception $ex) {
    //If you have mechanism to log or mail Exceptions
    Helper::logException($ex);

    //Rollback all previous transactions
    DB::rollBack();

    //Then we might want to redirect with some Error Message for the User
    return redirect()->route('form')->with('error', $errorMessages);
}

Luckily DB Facade controls both for Query Builder and Eloquent ORM.

Here is a simple code snippet for Automatic use of Transaction.

DB::transaction(function () {
    $user->save();
    $company->save();
    $department->save();
});

Here we don't need to manually Rollback. It does everything automatically. Only disadvantage I find of using it is we don't have control to fire email or show Error Message to the User.

Hope this helps.
Thanks
Debabrata

No comments:

Post a Comment