Database Transactions in Laravel
Sometimes we require to do bulk insert/update/delete operation in database, or chained database operations, and if any exception occurs at any step, it should not perform any database operation in the chain.
“Transactions” gives us power to commit a group of database operations, like bulk insert, or rollback the entire transaction if any error occurs.
Laravel provides very easy API for Transaction. Recently, we needed to parse multiple CSV files having around 50k records each, where it should delete all records first and then insert all records in database.
Laravel provides DB::beginTransaction() method to begin transaction and within try — catch block, to commit the transaction DB::commit() and to undo / rollback, we have DB::rollback(). Here is a simple example showing how to use Transactions in Laravel.
As you might note, we insert bunches of 10,000 records. We can change this limit as per our need / database server.
So here in our example, if any exception gets thrown at delete operation or any insert operation in the while loop, the transaction is rolled-back in the catch block, and none of the database changes occur. And if all goes well, we commit the transaction.
So, next time thinking to use Transactions in your Laravel project? All the best!
Any questions or suggestions? please comment!
RadicalLoop is a web development company. Follow RadicalLoop on Twitter, Facebook. 🚀