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
Let
PHP
parse your syntax here. It must load$this->meta
anyway, because whenPHP
parses your code, it takes precedence over thewhenLoaded()
method.This is why
whenLoaded()
can be usedclosure()
to avoid loading relationships unless they are actually loaded. This method will first evaluate the closure after thewhenLoaded()
condition is met.