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

[5.6] Add withDefault() support to MorphTo relationships #24061

Merged
merged 1 commit into from
May 2, 2018
Merged

[5.6] Add withDefault() support to MorphTo relationships #24061

merged 1 commit into from
May 2, 2018

Conversation

staudenmeir
Copy link
Contributor

Adds withDefault() support to MorphTo relationships:

public function commentable()
{
    return $this->morphTo()->withDefault();
}

The tests are taken from DatabaseEloquentBelongsToTest.

Fixes #24055.

@taylorotwell taylorotwell merged commit 43e4bc3 into laravel:5.6 May 2, 2018
@vpratfr
Copy link
Contributor

vpratfr commented Jul 2, 2018

Hi,

I am the person who originially opened #24055.

I fail to understand how calling ->withDefault() could determine how to create the related model instance.

According to me, this should throw an exception because the Comment class has no idea what to create as default (a video or a post?)

So the only valid use case of withDefault for MorphTo is when you provide a dynamic callback.

For instance:

FooModality extends Model

BarModality extends Model

Mission extends Model  
    has attributes : 'template', 'modality_type', 'modality_id'

    public function modality() : MorphTo {
        return $this->morphTo('modality')
                ->withDefault(function() {
                    // Eloquent needs to update our 'modality_type', 'modality_id' columns
                    if ($this->template==='foo') return new FooModality();
                    if ($this->template==='bar') return new BarModality();

                    throw new IllegalArgumentException("Mission type is not handled");
                });
    }

If we want to be able to use withDefault() then we need to introduce somehow a mecanism to decide which class of related model to instanciate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants