laravel model prevent lazy loading throw exception when using "whenLoaded()" for relation in resource

Issue

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

Solution

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; });

Answered By – mrhn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published