In this episode, we tackle the problem of reusing the view logging functionality across multiple models in our Laravel app. Up until now, we just had this on one model, which meant having to copy and paste code if we wanted it elsewhere—not ideal! So, we start by creating a new Discussion
model that should work the same way and store view counts.
To avoid duplication, we set up a new trait (we called it LogsViews
), shoved the needed functions in there, and used Laravel's model features to make everything more dynamic (like using getTable()
and getId()
so the trait works with any model it's applied to). We test this on the new Discussion model and confirm it logs and retrieves views just like our original Article model.
Next, we update our sync
command (the one that writes the view counts back to the database) so it's not just for articles, but can handle multiple models. We add an array of models to sync, loop through them, and make sure the trait's logic works for each. We test it out by visiting articles and discussions, then running the command and checking the database—everything updates correctly!
By the end, you’ll see how to use a trait to keep code DRY and update batch processes to handle multiple models at once. This not only makes your codebase cleaner, but super flexible if you need to add even more models in the future!