Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 12, 2021 01:42 pm GMT

What is DB:transaction and how to use it in laravel

Hello, in this blog we are going to see for what purpose and why we use DB:transaction and advantage of using it.

What is Database Transaction?
Database transaction is provided by DB facade to run a set of operation within a database transaction.
It gives us the powerful ability to safely perform a set of data-modifying SQL queries such as insert, update, delete. It made safe because we can easily rollback all queries made within the transaction at any time.

Why we use it?
Let us consider we have an application on which admin can see all the posts and its user, which is associated with each other. When admin deletes post/user which is totally dependent on one another, and if any one of its operation fails we need to rollback previously successful operation to prevent error causing issues and send a error message back to the admin.

Let us see an example:
Issue causing scenario

 // delete user and all of its post $user = auth()->user(); $user->posts(); $user->delete();

In the above example user will be deleted but it's posts are not deleted, which will cause error where we are using post with its user_id, or these posts are still there in database which is now unused and unnecessary. To prevent this we use Db transaction, so if the posts are not deleted we cannot delete its user (because the operation are dependent on each other) and it will rollback the transaction.

We can now use the below code.

 // delete user and all of its post DB::transaction( function () {    $user = auth()->user();    $user->posts()->delete();    $user->delete(); });

This is how we can handle the issue with DB transaction. If both transaction succeed then with will return success message.

Thank you for reading.


Original Link: https://dev.to/snehalk/what-is-db-transaction-and-how-to-use-it-in-laravel-1i4m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To