Ahmad Mohammad Kouja
Ahmad Mohammad Kouja

Reputation: 58

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

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

Answers (1)

mrhn
mrhn

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

Related Questions