Truncate MySQL Causes Implicit Commit

Feb 18, 2019 laravel mysql
This post is more than 18 months old. Since technology changes too rapidly, this content may be out of date (but that's not always the case). Please remember to verify any technical or programming information with the current release.

I guess I should RTFM more often… but I didn’t remember (or know??) that MySQL truncate table causes an implicit commit.

I was doing unit testing in Laravel using the database transactions trait. Part of my seed data has a dataset. I wanted to get rid of all of that data so I could start fresh in one singular test. So, I started out writing the test like this: MyModel::truncate(). I couldn’t figure out why all of my test data kept getting all messed up then. Turns out, the database transaction can’t protect against implicit commits! Doh!

So, instead, I did this: MyModel::getQuery()->delete(). Then, it was fine with the transactions.

Side note: This article is not me condoning seeding data and then truncating it for unit tests. It just happened to be my circumstance at the time.

Looking for more Laravel Tips & Tricks? Join Joel and I on the No Compromises bi-weekly podcast; around 15 minutes of thoughtful real-world advice and helpful info.
Go to All Posts