You need to use a function (closure) for the actual returning of the relationship. Otherwise php will run it.
Jan 28, 2023
3
Level 27
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
])
];
}
Level 102
1 like
Please or to participate in this conversation.