Skip to content
Advertisement

Laravel / League Fractal returns an empty array instead of empty object

I’m having a problem with Fractal library. I’m using Spatielaravel-fractal library which is just wrapper for Leaguefractal. 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?

Advertisement

Answer

I just encountered the same problem. I wanted to return empty array instead of NullResource. Here is what I was able to find from the source code.

Instead of $this->null(), $this->primitive(null) did the trick. You can enter whatever you want to be returned.

In your case $this->primitive(new stdClass()) should be the way to go.

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement