POLYMORPHIC NAMING METHOD CONSTRAINTS
Feb 02, 2024 Copy Link
First, let's use the table structure that Laravel used. In addition, we 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 illustrated you should define the `imageable`
relationship method in the `Image`
model to access whether the `User`
or `Post`
models instances, but if you misspell the method name and write imageablle
instead of imageable
an exception will be thrown. The reason behind that is 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');
}