Reputation: 58
i recently start using Model::preventLazyLoading()
but it actually throws an error even when the relation is not loaded but it may be loaded sometimes
like this in resource 'discount' => $this->whenLoaded('meta', $this->meta->discount ?? 0),
laravel version: 9.17.0
Upvotes: 2
Views: 1360
Reputation: 18976
For PHP
to resolve your syntax here. It has to load $this->meta
no matter what, as it has precedence over the whenLoaded()
method, when PHP
parsers your code.
$this->whenLoaded('meta', $this->meta->discount ?? 0)
That is why whenLoaded()
can take a closure()
to avoid loading relationship, unless they are actually loaded. This approach will first evaluate the closure after the whenLoaded()
condition is met.
$this->whenLoaded('meta', function () { return $this->meta->discount ?? 0; });
Upvotes: 2