In this episode, we tackle the issue of our 'like' functionality being limited just to comments. What if you wanted users to like articles, courses, or any other model in your app? Instead of re-coding the same logic over and over, we refactor our code to be much more flexible.
The solution: we create a Likable
trait! We move all the like-related code out of the Comment
model and into this reusable trait. This way, any model (not just comments) can be 'likable' simply by using this trait.
We then ensure the like functionality is model-agnostic by using the model's actual table name and its ID to generate Redis keys. So if you ever want articles or videos to be likable, just add the trait—no more code duplication or messy keys.
Finally, we test it out by applying the trait to comments and see that everything still works perfectly. And you’re ready to extend likes to any model in the future with almost no extra work.