In Laravel how to use snake case for database tabl

2020-07-13 11:12发布

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?

2条回答
成全新的幸福
2楼-- · 2020-07-13 11:18

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() );
查看更多
地球回转人心会变
3楼-- · 2020-07-13 11:25

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. :D

查看更多
登录 后发表回答