DEV Community

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

Posted on

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!

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