I recently started using Model::preventLazyLoading()
But even though the relationship is not loaded but sometimes it might be, it actually throws the error
Like resources 'discount' => $this->whenLoaded('meta', $this->meta->discount ?? 0),
laravel version: 9.17.0
P粉9208354232024-01-06 11:06:13
Let PHP
parse your syntax here. It must load $this->meta
anyway, because when PHP
parses your code, it takes precedence over the whenLoaded()
method.
$this->whenLoaded('meta', $this->meta->discount ?? 0)
This is why whenLoaded()
can be used closure()
to avoid loading relationships unless they are actually loaded. This method will first evaluate the closure after the whenLoaded()
condition is met.
$this->whenLoaded('meta', function () { return $this->meta->discount ?? 0; });