Skip to content

[Bug]: Defined morphMap is ignored #43

@schakko

Description

@schakko

What happened?

If you define a morph map like

Relation::enforceMorphMap([
    'post' => 'App\Models\Post',
    'video' => 'App\Models\Video',
]);

in your Laravel application then CreateRelatedRecord::associateRecordWithParent still uses App\Models\Post as morph type and not post.

Bugfix:
Change CreateRelatedRecord::associateRecordWithParent to

    protected function associateRecordWithParent(Model $record, Model $owner)
    {
        /** @var HasMany $relationship */
        if (($relationship = $this->getRelation()) instanceof HasMany) {
            $record->{$relationship->getForeignKeyName()} = $owner->getKey();
        }
        if (($relationship = $this->getRelation()) instanceof MorphMany) {
            $record->{$relationship->getForeignKeyName()} = $owner->getKey();
            // FIX: use getMorphClass() instead
            $record->{$relationship->getMorphType()} = $owner->getMorphClass();
        }

        return $record;
    }

How to reproduce the bug

See above.

Package Version

1.2

PHP Version

8.3.7

Laravel Version

11.22.0

Which operating systems does with happen with?

Windows, Linux

Notes

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions