In this episode, we dive into the super common one-to-many polymorphic relationship that you’ll often use in Laravel’s Eloquent ORM. Basically, we’re setting up a classic comment system: both articles and episodes can have many comments (sound familiar?). We start by quickly creating models and migrations for articles, episodes, and comments, focusing on simplicity and leaving out unnecessary stuff for now.
We go through setting up the migrations, paying special attention to the morphs
method to make the comments polymorphic. Then we move to the models, where we add the morphMany
and morphTo
relationships so everything links up nicely (just like a regular one-to-many, but with the polymorphic twist). We also make sure to hook up Laravel’s morph map in the service provider so Eloquent knows how to retrieve these related models.
To wrap up, we try things out by creating some episodes and articles and confirm that you get a collection of comments with your articles or episodes. We peek at what happens when you query the relationships and touch on how you’d insert comments related to different models. Next up, we’ll look at actually inserting these relationships in real-world code!