Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 480
Michael Avatar asked Oct 24 '13 16:10

Michael


People also ask

Should I use snake case or camel case?

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.

What is snake case in SQL?

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.

Is JavaScript snake case or camelCase?

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.


1 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() );
like image 72
Antonio Carlos Ribeiro Avatar answered Jan 01 '23 08:01

Antonio Carlos Ribeiro