0

I am using Fractal Transformers in one of the Laravel based REST API project. I have a $defaultInclude and thus have a function in the Transformer class(ReleaseTransformer) to process the includes. It is as follows :

public function includeDetails($item)
{
    $details = $item->details;

     return $details
        ? $this->collection($details, new DetailsTransformer())
        : $this->null();
}

and in DetailsTranformer class I have

public function transform($item)
{
    return [$item->detail];
}

I am getting the correct data here, but the response is as follows :

"details": {
     "data": [
          [
              "DETAIL-ID-1"
          ],
          [
              "DETAIL-ID-2"
          ],
          [
              "DETAIL-ID-3"
          ],
      ]
  }

I would like to get the response as an array like the following:

"details":["DETAIL-ID-1", "DETAIL-ID-2", "DETAIL-ID-3"]

I am using the extension spatie/laravel-fractal and the response is obtained by using :

fractal($release, new ReleaseTransformer())->toArray();

How can I modify the code as it will return this array ?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Happy Coder
  • 4,255
  • 13
  • 75
  • 152

1 Answers1

0

I found a workaround for this. We can use the flatten() method of Laravel collections and it will make the returned array single dimensional. So the code will be as follows :

$data = fractal($release, new ReleaseTransformer())->toArray();

$dataAsArray = collecet($data)->flatten()->all();

PS: I am not sure it is a correct to use transformers for the scenario I have mentioned, but just putting the answer if someone needs it.

Happy Coder
  • 4,255
  • 13
  • 75
  • 152