fractal icon indicating copy to clipboard operation
fractal copied to clipboard

Filtering out elements where value is null in Transformer

Open kickthemooon opened this issue 7 years ago • 4 comments

Example:

return [
  'name' => null
]

This element is not filtered out. Is there some way to tell Fractal to filter out null elements or does it have to be done manually?

kickthemooon avatar Aug 02 '18 08:08 kickthemooon

It'll have to be done manually, this is not really in the scope of Fractal.

If a value is meant to be in the response but there is no value for it, the property should still be there but not have a value in my opinion, otherwise you're putting responsibility on your consumer to check if the keys are there in the response, which shouldn't happen.

Imagine every property on the object needing the API consumer to check if it exists?

willishq avatar Oct 12 '18 15:10 willishq

i totally agree with @willishq .. it is better to have a "stable interface / structure" for the return types of a transformer..

however, if you want to filter out some properties that are explicitly set to null you can use the array_filter() method.. please note that this function may also remove falsy values, like false or ''..

I think, this issue can be closed @kickthemooon

johannesschobel avatar Jun 07 '19 07:06 johannesschobel

I think both ways are valid. I prefer keeping the key, but I can see why some people might want to remove null values from response (eg. to reduce network usage or hide some fields). But for that the best way is to create a custom serializer (or modify existing one). The default should still be keeping the keys.

Also maybe having a way to say that something does not exist (as opposed to being empty) might be a solution. So adding a new keyword like this:

protected $defaultIncludes = [ 'a',  'b',  'c'];

public function includeA($item)
{
        return $this->primitive(1);
}

public function includeB($item)
{
        return $this->null();
}

public function includeC($item)
{
        return $this->skip();
}

To return

{
  "a": 1,
  "b": null
}

hubertnnn avatar Jun 23 '21 15:06 hubertnnn

This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 4 weeks if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 16 '22 06:04 stale[bot]