Home » Php » Eloquent mapping API attributes to field names

Eloquent mapping API attributes to field names

Posted by: admin October 29, 2018 Leave a comment

Questions:

I have an app that sends to an API an object like this:

{id: 4, foo_id: 4, numberOfBars: 2}

The Laravel backend has a database table with fields like this:

id, foo_id, number_of_bars

I’m currently mapping the API keys to table names in an array, like so:

$map = [
    'id' => 'id',
    'foo_id' => 'foo_id',
    'numberOfBars' => 'number_of_bars'
];

and using this to create a new load of data to pass to the Eloquent model. This seems inefficient. Is there a way to do this more efficiently in Eloquent? I can’t create a catch-all method because as you see some keys are in camelCase and some aren’t.

Answers: