Courses

Laravel 12 Eloquent: Expert Level

Advanced Polymorphic: Many-to-Many

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Implementing complex polymorphic relationships
- Setting up pivot tables for polymorphic relations
- Managing many-to-many polymorphic queries
- Understanding relationship directionality

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

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 38 video+text lessons of this course? (1 h 34 min)

You also get:

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