javascriptphplaravelreactjsdingo-api

Eloquent model attributes as camel case [Laravel 5.2] [Dingo API]


Our Eloquent models have attributes following the Laravel snake case convention.

e.g. first_name, last_name and created_at

Although my frontend (react) follows the javascript camel case standard.

e.g. firstName, lastName and createdAt

Is there a simple way to convert ALL attributes to camel case when sending an API response?

We are using Larave 5.2 and the Dingo API package.


UPDATE

Following on from the accepted answer I used the Custom Response Format approach. See the following gist for the implementation (includes unit tests):

https://gist.github.com/andrewmclagan/c5e0fe601d23f3b859b89a9f8922be68


Solution

  • You really have a few options. I won't go into implementing them (unless needed), but here are a few I can think of:

    In Laravel:

    In Dingo:

    Any one of these options should be able to do the job, it's just a matter of how global or granular you want these transformations to be. For example, modifying toArray() will affect all code that converts your model to an array (or json), not just your response code, so you may not want your change to be that global.

    I would think that the Custom Response Format is probably the best combination of ease and appropriateness for your situation.