How to lazy load nested relationship? #104
-
When I need to load a nested relationship with Laravel Resources I can do something like: // Loading the relationship
new ModelResource(Model::with('foo.bar')->get());
// Relevant ModelResource part
$this->whenLoaded('foo', fn () => $this->when(
$this->foo->relationLoaded('bar'),
fn () => $this->foo->bar->baz
)
) I've tried the following with no luck: Lazy::whenLoaded('foo.bar', $model, fn () => $model->foo->bar->baz)
Lazy::whenLoaded('foo', $model, fn () => Lazy::whenLoaded('bar', $model->foo, fn () => $model->foo->bar->baz)) How can I achieve this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @benjivm, At the moment we do not have support for this kind of checking. This is actually also quire complicated to achieve. In the case of simple relations with a 1:1 mapping there's no problem. For example if For example let say the In this case I would opt for using a conditional Lazy where you write the condition of relations loaded out manually. |
Beta Was this translation helpful? Give feedback.
Hi @benjivm,
At the moment we do not have support for this kind of checking. This is actually also quire complicated to achieve. In the case of simple relations with a 1:1 mapping there's no problem.
For example if
foo.bar
is requested, we first check iffoo
is loaded on our model and then we check ifbar
is loaded onfoo
. If that's the case the lazy closure can be executed. But as soon as we add relations with multiple models to the mix we start to get in trouble.For example let say the
foo
relation is actually a collection of model, now we need to check if eachbar
relation is loaded on all thefoo
models.In this case I would opt for using a conditional Lazy where you write the condit…