So I am currently building out an API and see that laravel has added an API resource which I am assuming is in lieu of something like fractal?
However running into an issue where when I go to return a collection using the XyzCollection resource I do not have the ability to change my DB names? So i end up with the same naming convention I have in my DB..
Plenty of obvious reasons why I don't want to have that be the case (i can go into them if need be) HOWEVER - is there a way to alter those key names?
for example in one of my tables I have a id,uuid,user_uuid Now in fractal I would just transform these fields like so -
'id' => $xyz->uuid,
'user' => [
'data' => [
[
'user_id' => $xyz->user->uuid,
'username' => $xyz->user->username,
]
]
],
How do i do this when all i can do is pass in the collectionin the XyzCollection?
'data' => $this->collection,
and before you say use XyzResource ... When I am returning all(); records like I need to do plenty of times in an API (or paginate) etc etc. I can only do that from XyzCollection!
Thanks in advance
Steve
You first need to define a structure for a singular JsonResource object:
(
php artisan make:resource Xyz
)And then tell your XyzCollection to use the class:
(From https://laravel.com/docs/5.7/eloquent-resources#concept-overview)
If your ResourceCollection doesn't do anything extra, you might not always need it. Every JsonResource can transform itself into a resource collection with the
collection()
method, e.g.UserResource::collection($users)