Simple Record History Tracking with Laravel Observers

Photo by Teddy Kelley

I had a client recently that wanted to track changes made to certain database records and who had made them. He was basically asking for a written history of any record in the specified tables. Laravel makes this absurdly easy with model observers and polymorphic relationships.

First, let’s set up our history table:

Laravel model observers work by hooking into model events and allow you to, well, observe them. You can alter the model before continuing, cancel an event that is currently happening, or in my case, handle an action after an event was fired.

I wanted to be able to implement this very uniformly for any model that needed history tracking. Ideally, I wanted something like this:

I got there, and also allowed for a customization when necessary. I created a trait so that it would be easily reusable across various observers:

Thanks to polymorphic relationships, fetching the history of a model is simple:

And there you have it! Painless record history tracking with Laravel.