laravel model prevent lazy loading from throwing exception when using "whenLoaded()" relationship in resource
P粉614840363
P粉614840363 2024-01-05 21:36:19
0
1
528

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粉614840363
P粉614840363

reply all(1)
P粉920835423

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; });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template