2

I'm having a problem with Fractal library. I'm using Spatie\laravel-fractal library which is just wrapper for League\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?

Buglinjo
  • 2,067
  • 1
  • 15
  • 26
  • Instead of `$this->null()` you could just return `new stdClass()` (for the empty object) – ljubadr Jan 10 '19 at 23:18
  • @ljubadr It won't work as this function is expected to return `League\Fractal\Resource\ResourceInterface` – Buglinjo Jan 11 '19 at 15:26
  • Does `$this->item(null, new DocumentTypeTransformer)` work? – ceejayoz Jan 11 '19 at 17:25
  • Or you could return a `NullResource`, perhaps? https://github.com/thephpleague/fractal/blob/master/src/Resource/NullResource.php https://github.com/thephpleague/fractal/issues/124 – ceejayoz Jan 11 '19 at 17:26
  • @ceejayoz The problem is `new NullResource()` is always converted to an array. I have created an issue on their library GitHub page. Hopefully, they will fix it. – Buglinjo Jan 11 '19 at 18:46

1 Answers1

1

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

Ozan Kurt
  • 3,731
  • 4
  • 18
  • 32