Home > other >  Conditionally load laravel api resource
Conditionally load laravel api resource

Time:10-20

I'm trying to conditionally load a property (not a relationship) in my API Resource class:

'animals' => $this->when(false, AnimalsResource::collection($this->animals), null),

I thought that if the condition was false it wouldn't try to load the property animals. However when I run this I get the following error:

Call to a member function first() on null

How can I remove the property animals from my api response json when it is null?

CodePudding user response:

PHP needs to know all the parameters of a function before calling them.

Doing AnimalsResource::collection($this->animals) will actually generate the result so it can use it to call when.

You can try the following code instead:

'animals' => $this->when(false, function () { 
 return AnimalsResource::collection($this->animals); 
}, null),

in which case the parameter is a function instead of a collection which Laravel might invoke if the first parameter is true

CodePudding user response:

No, it doesn't. The 'when' method only applies to the Api Resource, but you are still invoking the animals property.

You could set something like this

'animals' => $this->when(! is_null($this->animals), AnimalsResource::collection($this->animals), null),

Keep in mind that if you are executing a SQL Statement inside your 'animals' attribute, you could generate a N 1 problem.

  • Related