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? (36 h 00 min)

You also get:

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

Already a member? Login here

Huthaifah Kholi avatar

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

Povilas Korop avatar

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

avrahamm avatar

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?

Povilas Korop avatar

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

👍 1
Lokith avatar

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

Povilas Korop avatar

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.

Lokith avatar

Okay thank for your response

Alex Kim avatar

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

Povilas Korop avatar

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

Alex Kim avatar

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

Povilas Korop avatar

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.