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...