Skip to main content

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

Read more here

Advanced Polymorphic: Many-to-Many

Premium
1:45

Now, let's look at the polymorphic relation, which is a bit more complex: a many-to-many polymorphic relation.

Suppose we look at the photos table from a previous lesson example. What if you want the same photo to belong to both a task and a user, or maybe to more models like the posts? This sounds like a many-to-many relationship, doesn't it?


Structure

So, what do we do for the polymorphic photos table? We remove the morph fields and create a separate pivot table called photoables.

Schema::create('photos', function (Blueprint $table) {
$table->id();
$table->string('filename');
$table->morphs('photoable');
$table->timestamps();
});

The photoables pivot table will have a foreign key column to the photos table and the same two morph columns ID and type.

Schema::create('photoables', function (Blueprint $table) {
$table->foreignId('photo_id')->constrained();
$table->morphs('photoable');
});

Then, in the Photo Model, we don't need the photoable morph relation. Instead, we must define...

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

FF
Francisco Ferreira Roque Júnior ✓ Link copied!

WOW, that lesson was amazing too, thanks

K
kalDeveloper ✓ Link copied!

Hi Can you please share the seeders, factories classes for this entier chapter (Advanced Eloquent Relations) ? I think for beginners it is bit difficult to stay on the tutorial. becasuse they have to spend some additional time on searching how to add seeders to polymorphic relations. if you add those , they will learn how to create seeders,factories for these kind of relationships. Thank you

M
Modestas ✓ Link copied!

Hi! The idea here was to showcase how methods are used, rather how factories work. So that is why there is no repository attached to this (and factories/seeders). Sorry.

K
kalDeveloper ✓ Link copied!

Hi how can we get the idea if we can't run and test this in a locally set up environment ? i don't think you encourge people to just read and understand the concept. can you please explain how to understand then ? i think when we buy a course we expect the course is fully ready with all the meterials it needs. no need to teach how factories works. at least if you can provide those code examples in repository, that would be really helpful.

M
Modestas ✓ Link copied!

To be honest, that is part of learning. Getting your hands dirty and trying to figure it out :)

But your comment is noted, we are trying to include repositories as much as possible, and probably missed this one. After Laravel 12 update, we should include it.