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

Bert Heyman @bertheyman

About: Laravel enthousiast, likes reading dev stories and the openness of communities like dev.to

Location:
Belgium
Joined:
Nov 6, 2017

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

Publish Date: May 29 '19
8 1

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!

Comments 1 total

  • webdeasy.de
    webdeasy.deMay 30, 2019

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

Add comment