In this episode, we dive into Laravel's one-to-one polymorphic relationships. While these are super flexible, they tend to be underused, possibly because their purpose isn’t always obvious at first.
We start off with a fresh Laravel project and talk about a common real-world scenario: sharing an image between different models, like Users and Posts. Instead of duplicating columns or creating a bunch of different tables (like user_images
and post_images
), a polymorphic relationship lets us tie an image to any model we want, now or in the future, using just one images
table.
We go step by step, creating the necessary models, migrations, and factories using Artisan. Then, we work through the database changes, showing you how the polymorphic columns (imageable_id
, imageable_type
) work. We also discuss Laravel's naming conventions, like using morphs('imageable')
to keep everything clean and conventional.
Once we’ve set up the tables, we jump into the model code, defining the actual relationship methods using morphTo
, morphOne
, and highlighting how these make the images accessible from both users and posts. We test this out in Tinker and explain why accessing the image returns null
until one is actually assigned.
Towards the end, we manually insert an image into the database linked to a user, see it showing up on the relationship, and then show how the same structure allows us to swap it over to a post easily. The big takeaway: if you need to connect a single resource to different kinds of models without creating lots of extra tables, one-to-one polymorphic relationships are the way to go. Next up, we’ll look at how to insert these records more easily from code.