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

Meh's avatar
Level 4

API Resource $this->when condition not respected

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)
				)
		];
}
0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

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);
})
Meh's avatar
Level 4

@Sinnbeck Legend! Guess i read the docs wrong. Thanks for the assist.

Sinnbeck's avatar

Did you mark your own answer as best by accident? :)

Please or to participate in this conversation.