Courses

Laravel 12 Eloquent: Expert Level

Polymorphic Relations: Explained with Example

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Understanding polymorphic relationship concepts
- Implementing model and migration structure
- Setting up polymorphic relationships
- Managing polymorphic queries

Polymorphic relations are challenging to understand at first glance. So, the best way to explain it is with examples. How do we use that structure without polymorphic relations?


Non-flexible Structure, or Polymorphic?

Imagine you have a users table and then a projects table, and then those projects are divided into tasks. So, there are three database tables, and you want to add a database table called photos.

The photo may belong to a project or a task. So, the tables could be project_photos, task_photos.

But what if a user also could have a photo-like avatar. So, another table would be user_photos? Each table would have a corresponding foreign key column like project_id, task_id, and user_id.

That's one way, but you probably feel something is wrong because it's all repeating except for the foreign ID field.

project_photos
- id
- filename
- project_id
- timestamps
 
task_photos
- id
- filename
- task_id
- timestamps
 
user_photos
- id
- filename
- user_id
- timestamps

Maybe there should be one table, photos? But then, foreign key to what? Another way is to have foreign keys belonging to all of them. So, three fields, one of which will be filled out, and the other ones will be null.

photos
- id
- filename
- project_id
- task_id
- user_id
- timestamps

But the problem with that approach, in addition to too many fields in the database with meaningless null data often, is what if you have a need for another table and the fourth field? So, the photo will belong to a post in the future. What about the fifth one? So, this is not a flexible structure.

Polymorphic relations are for any database table that belongs to many other dynamic tables.

So, the solution in polymorphic relations would...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 75 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord