Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Don't forget about DB queries when auditing model changes

You want a complete record

Joel Clermont
Joel Clermont
2025-01-02

From our daily Laravel tips email. Get the next one in your inbox.

I like using the laravel-auditing package when you need an audit trail of changes to your models.

Recently, I was reviewing an audit log for a particular model, and I was noticing some gaps in the logs that were recorded.

When I dug further into it, I found that there was a place where the DB builder was being used to update a record with the decrement operator. If you're wondering there is a valid reason for this, but it's outside the scope of this article. Because auditing is attached to the Eloquent model, this DB query was not being captured in the audit log.

This could also be caused when you do bulk updates with Eloquent, since that doesn't fire events per model instance.

Thankfully the package offers some custom auditing functionality which you can use to capture audit records after running the DB queries or your bulk Eloquent update.

You just need to make it a practice to remember to do this.

Here to help,

Joel

P.S. Sometimes a second set of eyes can be really helpful to figure out an annoying bug. The next time you're stuck, remember there's an option to Get Unstuck more quickly.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.