I have a model, Project, that I am eager loading relations in the Http/Controller.
The problem is that the withDefault closure on the belongsTo Relation in the model always fires, regardless of if there is an actual relation to eager load, resulting in many pointless queries and strange side effects.
This doesn’t seem like it should be expected behaviour – is there any way to stop it calling withDefault() unless it actually needs to?
To clarify:
return $project->loadMissing('address');
From the model:
public function address(): BelongsTo
{
return $this
->belongsTo(Address::class, 'address_id')
->withDefault(function() {
// This will always trigger
});
}
withDefault triggers always, regardless of the state of the actual relation.
2
Answers
Are you sure, when say ‘eager’ you executed your query using ‘with’ function?
Example:
In your Project model, you can define a boolean property to track whether the relationship was eager loaded. Then, you can override the load and loadMissing methods in your model to set this flag when loading relationships.
Then you can check in your closure if relation was eager loaded or not.