In this episode, we're taking a look at how to save records to a one-to-many polymorphic relationship in Laravel, specifically focusing on comments attached to articles (but the same approach could be used for any type of related model).
We start by reviewing how similar this process is to saving a one-to-one relationship—really, the main difference is that with one-to-many, we're dealing with collections of records, not just a single one. Then we walk through the entire workflow: building a new Comment
(typically from form input, but in this example we're filling in the details manually), and then saving it via the article's comments
relationship with the save
method.
After saving, we check it out in the database, confirming that the record is properly hooked up to the article. And, as a bonus, we mention how versatile this method is—it works just the same if you're commenting on something else, like an episode instead of an article. So wherever your form data comes from, if you build the comment with the right info, saving it to the related model's comments will just work.