Courses

Laravel 11 Eloquent: Expert Level

Advanced Polymorphic: Many-to-Many

Summary of this lesson:
- Implementing complex polymorphic relationships
- Setting up pivot tables for polymorphic relations
- Managing many-to-many polymorphic queries
- Understanding relationship directionality

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 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord