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?
Languages such as Java and Kotlin, which have a C and C++ heritage, use lower camel case for variables and methods, and upper camel case for reference types such as enums, classes and interfaces. Screaming snake case is used for variables.
Snake case (stylized as snake_case) refers to the style of writing in which each space is replaced by an underscore (_) character, and the first letter of each word is written in lowercase. It is a commonly used naming convention in computing, for example for variable and subroutine names, and for filenames.
However, the most recommended way to declare JavaScript variables is with camel case variable names. You can use the camel case naming convention for all types of variables in JavaScript, and it will ensure that there aren't multiple variables with the same name.
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With