fractal: Laravel - $this->null() returns an empty array instead of empty object
I’m having a problem with Fractal library. I’m using spatie\laravel-fractal library which is just wrapper for thephpleague/fractal. So…
I want to return an empty object instead of an empty array.
public function includeDocumentType(Question $question)
{
return $question->documentType
? $this->item($question->documentType, new DocumentTypeTransformer)
: $this->null();
}
$this->null() always returns [] after generation and I want to return {}. Tbh I want to have 2 functions like $this->nullItem() and $this->nullCollection().
Does anyone know what’s the solution to this problem?
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 8
- Comments: 20 (4 by maintainers)
I dont know if solve your problem. But you can try
And return is
this is dont {} but is better than []
I too am looking for an update on this. I’d personally like a null item resource to look like so:
An empty array or object doesn’t make any sense for a non-existent object.
Hello @buglinjo , @BRafols I have a similar issue, but i want to return null when include is empty (because return empty array is too weird). So, i’ve just implemented my own serializer:
And it works as expected for me. But if you try to change null to ‘{}’ or ‘new \stdClass()’ it will throw an error @KorvinSzanto , and it may cause an issue.
Also to return [] for empty collection you can just use anything like this
and it will return
"include":{"data":[]}with ArraySerializer, don’t sure about others. But $this->nullCollection() will be much easier and usefull i thinkI have an almost working POC. Im working with the other maintainers to figure out how to release it.
The plan is that the
NullResourceis going to be in line (as close as I can get it) to what is being discussed. However this would be a huge breaking change to anyone who currently relies on the null resource to be[], so I am adding a new EmptyResource which will be in line with what is the current behavior.The issue though is that this is a breaking change, so I dont want to unilaterally release something like this.
Thanks for your patience!
I’m also using the default serializer.
The most optinal, non-breaking and clean solution would be to allow the following two methods:
nullItemreturn an empty objectnullCollectionreturns an empty array@lucasres found the solution to this issue. Thank you!
Closing.