Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kiasaty's avatar

Morph to relationship

Hi,

I have these tables:

users, articles, images.

images could be for users, or articles, or none. I mean some images have no foreign_key. they have no relationships.

there are 3 solutions in my mind:

  1. use an eloquent Polymorphic Relationship, with nullable imageable_id and imageable_type columns. is this even possible?

  2. don't use a foreign_key in the images table. instead, create these pivot tables:

  • a "user_image" table with columns: user_id, image_id.
  • a "article_image" table with columns: article_id, image_id.
  1. do the previous method, but instead of using to pivot tables, use one pivot table with these columns: imageable_id, imageable_type
0 likes
2 replies
markss's avatar

Depends if your images can be for several users and articles at the same time, or if an image is always only for one instance of either.

If its possible to have more than one: Polymorphic many to many https://laravel.com/docs/7.x/eloquent-relationships#many-to-many-polymorphic-relations You will have to have an imageables table with columns image_id,imageable_id,imageable_type

Otherwise, if one image is only for one (or none): Polymorphic one to many https://laravel.com/docs/7.x/eloquent-relationships#one-to-many-polymorphic-relations You can keep the imageable columns on the images table directly

kiasaty's avatar

@markss I know about this. it's a one-to-many relationship.

My question is something else.

I'm asking if imageable_id and imageable_type can be null.

there are some cases that the image has no relationship.

Please or to participate in this conversation.