Using Transaction In Laravel

Transaction is a logical unit that is independently executed for data retrieval or updates. In the context of database, transaction is a unit that helps to manage data insert/update operation in elegant way. When we have to insert/update bulk data then it’s better to use transaction. If we have to add data in multiple table at once then, using transaction is great choice.

Database Transactions(Official Documentation)

We can easily tract error occurred during database operations so that we can make consistent database. We can commit the database operation if no error is encountered. In the same way, we can rollback the operations in case of error. Such way allows us to make complete database operation or nothing at all. Hence, There will be no partial insert or update in database.

Usage

In laravel, there are two ways of using transaction during insert/update operations. First way is to add all our operations inside a closure. In this case, closure will manage both commit and rollback operations automatically. Here is the example.

In above example, we have added two database operations inside a closure. There will be successful execution of both operations or nothing at all. In case of no error, transaction block ensures successful execution of both operations. In case of any error, above function will rollback the operations automatically.

Specific table migration in Laravel

We can manually handle these commit and rollback operations. This is another way of using transaction in laravel. We can start with begin transaction and then, commit or rollback based on success or failure of operations respectively.

In order to initiate, we can use following DB facade code.

Now, for successful operations without any errors, we can commit the operation with following code.

Display custom error message in Laravel

In case of any error or failure, we can easily rollback like this:

We can acheive best implementation of these actions in laravel using try and catch. Our overall structure of the code looks like following.

In above code, try/catch block encloses database operations by which allows us to detect errors. After successful database operations, commit action is executed. In case of any error, all actions are roll backed and exception will be thrown.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *