It will still be called, just not returned. Use a callback to fix it
$this->when($request->user()->can('permission') && $this->has_other_resource, function () {
return new OtherResource($this->relation->anotherRelation);
})
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm struggling to figure out what's going on here.
In the example below $this->relation does not exist, calling $this->relation->anotherRelation fails (which it should) but the condition for $this->when is false
$request->user()->can('permission') && $this->has_other_resource = false
Basically i'd like to know why this code is being called:
new OtherResource($this->relation->anotherRelation)
public function toArray($request)
{
return [
'some_key' => 'some_value',
'another_key' => $this->when(
$request->user()->can('permission') && $this->has_other_resource,
new OtherResource($this->relation->anotherRelation)
)
];
}
It will still be called, just not returned. Use a callback to fix it
$this->when($request->user()->can('permission') && $this->has_other_resource, function () {
return new OtherResource($this->relation->anotherRelation);
})
Please or to participate in this conversation.