The error message and your code suggest a misunderstanding of how Laravel's polymorphic relationships work.
Key Point:
For a MorphMany relationship, the foreign key columns (imageable_id and imageable_type) must exist on the related table—in this case, the images table, not a pivot table like imageables.
Why the Error Occurs
Laravel expects the images table to have imageable_id and imageable_type columns because that's how it links an image to its parent (e.g., a Video, Post, etc.) in a polymorphic relationship.
You do NOT need an imageables table.
The images table itself should have these columns.
Solution
1. Update Your Migration for images Table
Make sure your images table migration includes the polymorphic columns:
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('url');
$table->morphs('imageable'); // This adds imageable_id (unsignedBigInteger) and imageable_type (string)
$table->timestamps();
});
If your table is already created, you can add the columns with a migration:
Schema::table('images', function (Blueprint $table) {
$table->morphs('imageable');
});
Then run:
php artisan migrate
2. Creating Related Images
Now, you can create a video and attach images like this:
$video = Video::create(['url' => 'http://example.com/my_test_video.mp4']);
$video->images()->create([
'url' => 'images/post_image_1.jpg',
]);
This will automatically set the imageable_id and imageable_type fields on the new image.
3. Summary
- You do NOT need an
imageablestable. - The
imagestable must haveimageable_idandimageable_typecolumns. - Use
$video->images()->create([...])to create related images.
References:
If you follow these steps, your polymorphic relationship should work as expected!