changing key names when leveraging laravel resources to return API data

3.9k views Asked by At

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

1

There are 1 answers

3
Travis Britz On BEST ANSWER

You first need to define a structure for a singular JsonResource object:

(php artisan make:resource Xyz)

public function toArray($request)
{
    return [
        'user_id' => $this->uuid,
        'username' => $this->username,
    ];
}

And then tell your XyzCollection to use the class:

Customizing The Underlying Resource Class

Typically, the $this->collection property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailing Collection string.

For example, UserCollection will attempt to map the given user instances into the User resource. To customize this behavior, you may override the $collects property of your resource collection

(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)