In this episode, we're adding the ability to "like" comments in our application using Redis. First, we get a quick refresher on how Redis sets work by playing around in the Redis CLI—learning how to add members to a set (with SADD
), check how many members there are (SCARD
), and how the data is stored by key (like comments.1.likes
for storing likes on comment #1).
Next, we implement the like feature in our Laravel backend. We add an addLike
method to the comment model, which adds a user's ID to the Redis set for that comment's likes, using the Redis facade. Then, we wire this new method up to a simple POST route and build the corresponding form in our comments index, making sure to pass through the CSRF token and use route model binding. After naming our route, we test out the like button in the browser and verify that likes are being stored in Redis as expected.
We also add a convenient helper method (getLikeCount
) on the comment model to fetch the number of likes from Redis, and display this directly on our comments list. There's a quick chat about the automatic "uniqueness" of user likes, since Redis sets only allow unique values—so a user can't like a comment more than once.
Finally, we wrap up by mentioning that right now there's no way to "unlike" a comment, but that's what we'll tackle in the next episode. For now, you can like any comment and see the live like counter updating—backed by Redis!