Skip to content

Relation::tableNameAsMorphType breaks morphTo relations #35519

@dmason30

Description

@dmason30
  • Laravel Version: 8.17.2
  • PHP Version: 7.4
  • Database Driver & Version: MySQL 8

Description:

The #35257 PR doesn't seem to work with morphTo relations. You end up with an Class 'posts' not found when using in conjunction with Relation::tableNameAsMorphType();

Error : Class 'posts' not found
/src/Illuminate/Database/Eloquent/Relations/MorphTo.php:180
/src/Illuminate/Database/Eloquent/Relations/MorphTo.php:129
/src/Illuminate/Database/Eloquent/Relations/MorphTo.php:115
/src/Illuminate/Database/Eloquent/Builder.php:597
/src/Illuminate/Database/Eloquent/Builder.php:566
/src/Illuminate/Database/Eloquent/Builder.php:534

Steps To Reproduce:

Taking the example from the docs where imageable could be a Post or a User.
https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-polymorphic-relations:

class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}

Add the below to AppServiceProvider in the boot method:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {     
        Relation::tableNameAsMorphType();
    }
}

The below code will throw the exception described above:

$post = Post::factory()->create();

$image = Image::factory()->create([
    'imageable_type' => $post->getTable(), // 'posts'
    'imageable_id' => $post->id,
]);

// This will throw the exception
$postTitle = $image->imageable->title

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions