How you return the response is less relevant to how you organise and structure the data; personally I prefer to use either Transformers or API Resources over returning the Eloquent model directly.
Apr 30, 2020
5
Level 13
Api results Resource or json?
Hello Guys hope you are oaky.
I am wondering about best practice about return data in api requests?
So far i make Vue component for display images in gallery without refreshing, however how it will be better?
User resource for return data or
return response()->json()
Level 104
It is largely irrelevant how you use the resource on the frontend; but, if your frontend needs JSON, then a consistent API does matter. In that case, the API Resource makes perfect sense; but, if your needs are really so simple, and unlikely to become more complex, you can simple build the array representation in the controller:
$images = // some eloquent query
return response()->json(
$images->map(function ($image) {
return [
'id' => $image->id,
'path' => $image->path,
'caption' => $image->caption,
// ...
];
})
);
Please or to participate in this conversation.