Home » Php » In Laravel how to use snake case for database table columns and camel case for model attributes

In Laravel how to use snake case for database table columns and camel case for model attributes

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am new to laravel 4 and I am trying to create a rest API following best practices defined by Apigee.

One of the best practice defined by apigee is to use camel case for json attribute keys, this way when using the API in Javascript the corresponding objects will follow attributes code convention (camel case).

I want to be able to define datatable columns following snake case but when retrieving eloquent objects though my api, the corresponding JSON has to follow camel case.

I read about a static variable $snakeAttributes that could be set in the model class and its documentation says “Indicates whether attributes are snake cased on arrays”. I tried to override this variable and set it to false (MyResource class) but when executing the folowing code, the json still comes in snake case:

Code:

   $resource = MyResource::find($id);
   return Response::json($resource);

JSON:

{ 
first_name: 'Michael', 
created_at: "2013-10-24 15:30:01",
updated_at: "2013-10-24 15:30:01"
}

Does someone have an idea on how to solve that?

Answers:

Create BaseModel and a new method to help you with it:

class BaseModel extends \Eloquent {

    public function toArrayCamel()
    {
        $array = $this->toArray();

        foreach($array as $key => $value)
        {
            $return[camel_case($key)] = $value;
        }

        return $return;
    }

}

Your model:

class MyResource extends BaseModel {
}

And then use it:

$resource = MyResource::find($id);
return Response::json( $resource->toArrayCamel() );

Questions:
Answers:

The way I see, you’ll have to make a array, work manually on the keys (camel case) and then convert the array (not the result) on a JSON.

$resource = MyResource::find($id);  
$array = array();

foreach($resource as $key => $value) {
    $key = str_replace('_', '-', $key);
    $array[$key] = $value;
}
return Response::json($array);

I guess that will do the job. 😀