Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of API Resources?

I've read the docs and watched the Laracast. I'm still left wondering why you would use them?

I get that you can map different data to different names if your field names were to change but you want to keep a consistent public API. But surly you can just do the same on the model with the toArray() method and change the mappings there?

If I were to do:

return User::find(1);

I get a response like:

{"id":1,"name":"Ova Parker"}

If I do:

return new UserResource(User::find(1));

I get a response like:

{"data":{"id":1,"name":"Ova Parker"}}

Is there a significance in wrapping it with a data tag? I am just guessing but is this a standard JSON format for API's? Why would you not just do return User::find(1); instead of using an API resource, if this is under API routes then it'll return it as JSON anyway automatically.

like image 960
panthro Avatar asked Jan 08 '18 17:01

panthro


Video Answer


1 Answers

You kind of answer the question by yourself. The idea behind API Resources or Transformers (like the ones from Fractal) is to hide the db field names from the client. With return User::find(1) you expose your whole db structure which might not a good idea security-wise and also bad for the release process. If you need to change a db field name, you have to change the API too. With Resources you have a mapping between your application and the consumer of you API.

It seems more work in the beginning, but once you started it, you won't wanna miss it anymore.

There is no toArray() method in PHP, which gets magically called like __toString(). You have to write you own and call it by yourself. Resources are built-in by Laravel and will be resolved automatically.

like image 169
common sense Avatar answered Nov 04 '22 01:11

common sense