Skip to main content

Polymorphic Relations: Explained with Example

Premium
6:34

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 33 min)

You also get:

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

Already a member? Login here

Comments & Discussion

HK
Huthaifah Kholi ✓ Link copied!

what about down in migration file ? how to drop it?

PK
Povilas Korop ✓ Link copied!

Personally, I don't use down() method for a long time, Taylor said it back in 2017: https://laraveldaily.com/post/still-need-migrations-taylor-says-no

A
avrahamm ✓ Link copied!

Let's assume there is a PhotoController for polymorphic child resource

to manipulate Photo data.

Assuming Photo data is updated, then parent row,

either Project or Task, should be updated as well.

I see several options.

Option 1:

To create ProjectPhotoControler and TaskPhotoControler.

This way when inside ProjectPhotoControler,

$photo->photoable

is Project and may address Project fields by -> operator.

And same for Task.

In this case there is some code repetition,

yet dedicated controler may be more readable.

Option 2:

To create PhotoControler only,

yet will need if blocks to compare to photoable_type, like that

$if ($photo->photoable_type === Project::class){ ...}
$if ($photo->photoable_type === Task::class){ ...}

In this case, there is only one controler.

Yet, if there are more Owner Entities,

a lot of "if condition" blocks can make a code not readable.

Question: Can you please reccomend?

PK
Povilas Korop ✓ Link copied!

It's your personal preference, but I would go with PhotoController and if-else turned into match

L
Lokith ✓ Link copied!

Hi, could you please share the repository link for this course?

PK
Povilas Korop ✓ Link copied!

Sorry, there wasn't any repo for this course, as it was multiple small examples in this course so I didn't feel the need to save them as repository/repositories.

L
Lokith ✓ Link copied!

Okay thank for your response

AK
Alex Kim ✓ Link copied!

can i receive source codes related to polymophic explanations ???

PK
Povilas Korop ✓ Link copied!

Sorry when shooting this course I didn't save the source into repository

AK
Alex Kim ✓ Link copied!

nowaday, many lectures provide the source code. for example udemy... so i tald you

PK
Povilas Korop ✓ Link copied!

Yes I do provide the source code for courses that have one project created throughout the course. But not for courses where separate lessons are with small experiments like this one.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.