Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Laravel Polymorphic Relations

http://laravel.com/docs/eloquent#polymorphic-relations

Polymorphic relations allow a model to belong to more than one other model, on a single association. For example, you might have a photo model that belongs to either a staff model or an order model.

I don't really understand this use case. Does this mean that a member of staff could own a photo, or the photo could be placed in an order? Why not just put photo_id in staff table and photo_id in order table?

Could somebody please provide an alternative, simple to understand, example where polymorphic relations may be used?

like image 895
Gravy Avatar asked Nov 20 '25 16:11

Gravy


2 Answers

You can add the photo_id to Staff and Order, but with the morphMany relation type you don't have to 'clutter' all the models that are needing a Photo. When creating a third model that needs a Photo, just add the methods and you are done - no need for creating extra columns what so ever.

Also note you can specify the name. The manual uses 'imageable', but feel free to use multiple names for different types of Photo's (or other models)

like image 185
Rob Gordijn Avatar answered Nov 23 '25 09:11

Rob Gordijn


From what I understand, your view of the example provided in the Laravel Docs is flawed.

If you were to simply add a photo_id in both the staff and order tables, then each Staff member could only have one photo, while an Order could only have one photo. One photo can only either belong to a Staff member or an Order, but one Staff member or one Order can have multiple photos.

like image 38
Vincent Ghyssens Avatar answered Nov 23 '25 09:11

Vincent Ghyssens