Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Defined morphMap is ignored #43

Open
schakko opened this issue Sep 7, 2024 · 0 comments
Open

[Bug]: Defined morphMap is ignored #43

schakko opened this issue Sep 7, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@schakko
Copy link

schakko commented Sep 7, 2024

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

@schakko schakko added the bug Something isn't working label Sep 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant