Search code examples
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:

    • Override the toArray() method on the model. When a model is converted to JSON, it calls toArray(). You can use this method to go through and convert all the keys to camelCase. You would need to override this on every model, though, but that can be abstracted through a parent class or a trait.

    In Dingo:

    • Use Transformers with the Response Builder. You could create a transformer for every model, or you could create one CamelTransformer and register it with every model. You would convert the keys to camelCase in the transformer.

    • Create a Custom Response Format. You can create a camelJson response format that extends the default json format. Override the necessary methods with the logic to camelCase the keys.

    • Use the ResponseWasMorphed event. You can create an event handler for the ResponseWasMorphed event, and go through and camelCase your keys in there.

    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.