Replies: 2 comments
-
Yeah, I mentioned that in #44004, but they never followed-up on that as the core team is eager to close issues on formalities. |
Beta Was this translation helpful? Give feedback.
0 replies
-
From what I see in the docs, the withDefault is used to return a model. If you need to fill that model, you use the callback param. And that says it all. Do not use withDefault for nullable relations. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I've encountered an unexpected behavior with the withDefault method callback in Laravel when using composite keys. Although in the following snippet I'm using the Compoships package to define a relationship through composite keys, the issue lies in the core behavior of Laravel's withDefault method and not in the way the relation itself is defined. I only choose this example to show a case where the suggested change would be relevant.
I noticed that even if the callback within withDefault returns
null
, the relationship still returns a model instance. This behavior contradicts the expected outcome, as one would assume that returning null from the callback would result in a null default model for the relationship.This is the line which is responsible to return a model instance even when the callback returns null:
https://github.com/laravel/framework/blob/fb14d4326b780a9b2087caf7f12440f45a0f385c/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsDefaultModels.php#L54-L54C71
While one might argue that withDefault ensuring a model instance in all cases is desirable, I believe that passing a callback should act as the definitive way to define the default model. Therefore, it would be more consistent and intuitive if the framework honored a null return from the callback as the absence of a default model.
Beta Was this translation helpful? Give feedback.
All reactions