DEV Community

Cover image for Need a cmd + Z in your database? Transactions to the rescue!
Bert Heyman
Bert Heyman

Posted on

4 1

Need a cmd + Z in your database? Transactions to the rescue!

Let's say you're opening a new chocolate bar shop.
You're a bit of a Willy Wonka, so every week you upload newly invented products into your database:

  • Create new product categories
  • Insert new products and link to categories
  • Add related prices

If the creation of new product categories fails, the product might miss a category. Vice versa, a price for a non existing product has little use to the world. Determined to enrich the world with new ideas every week, you start looking for a solution: database transactions.

In short: your import will be all or nothing.

If anythings fails, nothing is changed in the database. Your data will only be updated if everything is working fine.

This feature is often overlooked, but isn't too hard in Laravel:

DB::transaction(function () {
    // An exception will rollback evertything in the database transaction
    DB::table('product_categories')->insert($productCategories);
    DB::table('products')->insert($products);
    DB::table('prices')->insert($prices);
});

And that's it - you're done!

Further reading?

Any database tips you feel like sharing? Feel free to discuss in the comments!

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (1)

Collapse
 
webdeasy profile image
webdeasy.de

Nice title and great post!
I think transactions is feature, that so many developers don't know! :/

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!