Home  >  Q&A  >  body text

laravel model prevent lazy loading from throwing exception when using "whenLoaded()" relationship in resource

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粉614840363P粉614840363262 days ago381

reply all(1)I'll reply

  • P粉920835423

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

    reply
    0
  • Cancelreply