In this episode, we're using a bit of imagination to picture a UI where users and posts can both have images uploaded and attached to them. The key focus here is on flexibility—whether we're dealing with a user or a post, we should be able to handle images in a generic way.
We walk through the process of associating an uploaded image with a user. Instead of manually setting things like imageable_type
and imageable_id
on the image (which you might sometimes see), we show how to use Eloquent's relationship methods to handle this for us. This makes the code cleaner and less error-prone.
You'll see in action how we can create an image, save it via the user's relationship, and Laravel will fill in all the necessary details behind the scenes. After sorting out a quick mass assignment error (with a discussion of fillable
vs guarded
on models), we repeat the same operation with a post just to prove it works no matter which model we're dealing with.
By the end, you'll have a solid grasp on saving one-to-one polymorphic relationships in Laravel, keeping your code neat and making use of Laravel's features rather than coding things manually.