In this episode, we're focusing on how to remove likes from comments. First, we start by duplicating our existing route for liking a comment, then switch it over to use the DELETE HTTP method for removing a like. We update the route name to something appropriate, like destroy
, and adjust the controller logic accordingly.
Next, we jump into our Comment model, and add a new method called removeLike
, which leverages Redis—specifically the srem
command—to remove the user's ID from the set of users who have liked the comment. It's basically the opposite of the add like functionality!
Then, we update our front-end Blade form so that if a user has already liked a comment, submitting the form will hit the destroy route and use method spoofing to send a DELETE request. That way, the form handles both liking and unliking in a really neat and conditional way.
Finally, we do a quick test to make sure everything works as expected. We see that clicking the button removes a like, and we can re-like as needed. The overall approach is pretty flexible, and although you might use different stacks like Livewire or Inertia, the general concept stays the same—make it easy to remove a like if one already exists.