First, let's use the table structure that Laravel uses. In addition, we're gonna seed the `images`
table:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\{User, Post, Image};
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
Image::factory()->count(3)->for(
User::factory(),
'imageable'
)->create();
Image::factory()->count(3)->for(
Post::factory(),
'imageable'
)->create();
}
}
As Laravel illustrates, you should define the `imageable`
relationship method in the `Image`
model to assess whether the `User`
or `Post`
model instances, but if you misspell the method name and write imageablle
instead of imageable
an exception will be thrown. The reason behind that is that the morphs column name should match the relationship method name
Behind the scenes, if you do not provide a name to the `morphTo`
method, Laravel will use the method name since that is most likely the polymorphic columns.
To resolve that exception, you should accurately write the relationship method name, OR keep the method name as you have defined and override the default parameters of that method:
public function imageablle(): MorphTo
{
return $this->morphTo('imageable', 'imageable_type', 'imageable_id');
}