In this episode, we're tackling how to set up polymorphic comments in our application so that comments can be attached to any model – not just one specific type like articles. We start by building out the comments table, thinking through what fields we need. That includes things like a nullable user_id
(for handling users who may be deleted later), the actual comment body, and a deleted_at
column for soft deletes. We also add a parent_id
to handle replies, making it nullable for top-level comments.
Then, we dive into the polymorphic part: adding commentable_type
and commentable_id
columns. This allows each comment to be linked to any model (e.g., Article, Post, etc.) in your app. We walk through the reasoning for using nullable morphs and why the child replies don’t need these fields set.
Next, we generate a Livewire Comments
component, wire it up to our article show page, and pass in the model we want to bind comments to. After establishing the polymorphic relationship in the model using morphMany
, we check out how it fetches all comments for an article. To test it, we manually add a comment in the database and see it appear on the page.
There's a great tip in here about using a morph map to avoid storing full PHP class namespaces in the commentable_type
field. Instead, we map it to simple, readable strings (like article
), making everything cleaner and safer if models ever get reorganized.
By the end, we've set up our database and Livewire component to fetch and display polymorphic comments for any model. Next up: we'll build the form to actually post comments. Stay tuned!