AndrewMcLagan AndrewMcLagan - 4 months ago 79
JSON Question

Laravel Dingo API - How to respond with multiple collections / transformers?

To initialize my app I have the following route:

/initialize


This returns Taxonomies, Enumerables and a couple of other taxonomy like collections. This saves multiple HTTP requests.

Although with Dingo / Fractal, I cannot see how I can respond with multiple collections?

e.g.

return [
'taxonomies' => $this->response->collection($taxonomies, new TaxonomyTransformer);
'enumerables' => $this->response->collection($enumerables, new EnumerableTransformer);
'otherStuff' => $this->response->collection($otherStuff, new OtherStuffTransformer);
];

Answer
return response()->json([
    'data' =>  [
        'taxonomies' => $this->fractal->collection($taxonomies, new TaxonomyTransformer);
        'enumerables' => $this->fractal->collection($enumerables, new EnumerableTransformer);
        'otherStuff' => $this->fractal->collection($otherStuff, new OtherStuffTransformer);
    ] 
], 200);

This should return the JSON in the format you are looking for.