DEV Community

Cover image for What is DB:transaction and how to use it in laravel
Snehal
Snehal

Posted on

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();
Enter fullscreen mode Exit fullscreen mode

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();
 });
Enter fullscreen mode Exit fullscreen mode

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. ๐Ÿฆ„ ๐Ÿฆ„ ๐Ÿฆ ๐Ÿ˜

Discussion (0)