Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Polymorphic Relations: Explained with Example

Premium
3:37

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

MM
Marek Miklúšek ✓ Link copied!

Hi there, just small mistake here:

Relation::enforceMorphMap 'user' => 'App\Models\Task', 'task' => 'App\Models\User', ]);

M
Modestas ✓ Link copied!

Whoops! Updated!

MM
Marek Miklúšek ✓ Link copied!

You are doing great job, love it, thank you:)

SA
Stephan Apenbrink ✓ Link copied!

Hi, how do you get for example Users or Tasks without having any photos ? If you have 4 Users and 3 are realted to photos with the morph or 10 Tasks but only 9 have photos ?

TG
Tyson Glore ✓ Link copied!

$users = User::doesntHave('photos')->get();