In this episode, we're taking our comments system to the next level by making it polymorphic—that means comments will be able to belong to any model type in our Laravel app (not just one specific thing like articles). This might sound a bit technical if you're new to Laravel, but we'll walk through it step by step and it starts to make sense as we go along.
We kick things off by setting up a quick example: we make an Article model, migration, and factory, keep things simple, and generate some sample articles. Then, we tie this into our routes and controller, wiring up article pages using route model binding so we can view them by their slug.
Once that's in place, we get into the core of polymorphism. Instead of tying comments directly to articles (using something like article_id
), we update our comments table using Laravel's morphs
helper. This gives us two new columns: commentable_type
and commentable_id
, letting comments reference any type of model, not just articles.
To clean up the way these types are stored, we use a morph map so our database only says "article" rather than a full namespace path. This futureproofs our DB if we end up moving models around later.
After wiring up the relationships in our models (using morphTo
and morphMany
), we test everything out by faking the creation of comments—showing how a comment ends up linked to the right article or anything else in the future. We even go over assigning the right user to a comment and make sure the relationships are all behaving as expected.
By the end, we've got a fully polymorphic comments system ready for use across different parts of our app. Next up, we'll work on displaying those comments and fleshing out the front end!