POLYMORPHIC NAMING METHOD CONSTRAINTS

Feb 02, 2024 Copy Link

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');
}

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autol...

    FREE

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE