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

bertheyman

Bert Heyman

Posted on May 29, 2019

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!

💖 💪 🙅 🚩
bertheyman
Bert Heyman

Posted on May 29, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related