Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brian Kidd's avatar

API Resource mergeWhen with conditional whenLoaded

I have lazy loading disabled and I'm trying to do this in an API Resource but whenLoaded is always evaluating to true. Any suggestions? I'm getting an error that I'm trying to lazy load rateable but expected whenLoaded would return false

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'expense_category_id' => $this->expense_category_id,
            'quantity' => $this->quantity,
            'task_category_id' => $this->task_category_id,
            $this->mergeWhen($this->whenLoaded('rateable'), [
                'rate' => $this->rateable->rate,
                'extended' => $this->rateable->rate * $this->quantity
            ])
        ];
    }
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You need to use a function (closure) for the actual returning of the relationship. Otherwise php will run it.

1 like
tisuchi's avatar

@brian kidd Does it work?

public function toArray($request)
    {
        $result = [
            'id' => $this->id,
            'expense_category_id' => $this->expense_category_id,
            'quantity' => $this->quantity,
            'task_category_id' => $this->task_category_id,
        ];

        if ($this->relationLoaded('rateable')) {
            $result = array_merge($result, [
                'rate' => $this->rateable->rate,
                'extended' => $this->rateable->rate * $this->quantity
            ]);
        }

        return $result;
    }

Instead of using $this->mergeWhen method, I use the relationLoaded method to check if the rateable relation is loaded and add the relevant information to the array.

Please or to participate in this conversation.