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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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! :/

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay