Hello Artisan 😎 , Database transactions are often an overlooked feature, but Laravel makes it so effortless.
One of the powerful ways to ensure data integrity is database transactions. Database transactions give a powerful ability to safely perform multiple database queries in a single transaction. If all queries run smoothly, then only it will commit otherwise it will roll back.
For Example, we have an application where we create a user, assign a role to the created user, and add KYC (Know your customer).
This all looks good. We don’t want any user without role and KYC but what if the user is not created. If the user is not created, we cannot assign a role and add KYC. This will cause errors in our system.
Here comes the Database transactions to the rescue :
As Laravel Documentation describes, all we have to do is wrap our database calls within a closure. If an Exception is thrown within the closure, then the transaction will roll back.
And that’s it ✌️ We’re done!