-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
Add withDefault() support to MorphTo relationships #24725
Comments
In addition to the previous message, it is also worth mentionning that the withDefault callback does not receive the appropriate parameter
|
not working in Laravel 5.6 |
Since #27411 was merged, I believe this issue is resolved. You can specify the morph type attribute ( public function getModalityTypeAttribute($value = null) {
if ($value === null) {
if ($this->needsFoo()) return FooModality::class;
if ($this->needsBar()) return BarModality::class;
}
return $value;
} The callback passed to public function modality() {
return $this->morphTo()
->withDefault(function($model) {
if ($model instanceof FooModality) $model->foo_attribute = 'something';
$model->general_attribute = 'something else';
});
} |
Your PR will be reverted. Causes failing tests on master. |
I'll re-open this so I can have a look later at some point. |
Thanks. I am struggling with how we are supposed to used the current code if that is meant to be sufficient to cover the needs for default morph related models. Closest would be to use the received parent model in order to return a new instance of the morphed related model.
In that case:
Seems a very different behaviour than |
This was fixed by #27455 |
Hi,
I am the person who originially opened #24055.
This is related to the fix in and its tests in #24061 which are not correct (unless I am wrong).
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 (if I follow the example used in the docs) the
Comment
class has no idea what to create as default (aVideo
or aPost
?)So the only valid use case of
withDefault
forMorphTo
is when you provide a dynamic callback.For instance:
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.For instance a function with a given naming convention could be provided in the model which has the
MorphTo
relationship:Then we could perfectly have
withDefault()
andwithDefault([...])
as valid use cases because they are able to know which class to instanciate.The text was updated successfully, but these errors were encountered: