1

I am using the full calendar open source library in an application. I am using Laravel at the back end. Now most JavaScript libraries use cameCase in their variable names. The thing is that on the back end Laravel has a naming convention in tables I guess which uses underscored_in_the_column_name.

Now the create() method comes very handy and creates a new resource with the input data coming and I don't have to assign multiple fields manually. But now since I am working with the library, it is sending the data as camelCase which is an issue both ways because when I return data from the server to the calendar I again have to make sure that the fields are in camelCase instead of underscores_between_them.

How do I do this? Is there a way to accomplish this in Laravel or will I have to do it manually?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Rohan
  • 13,308
  • 21
  • 81
  • 154
  • Try the answer [here](http://stackoverflow.com/questions/1993721/how-to-convert-camelcase-to-camel-case) – Matt Burrow Feb 27 '15 at 16:27
  • 1
    @MattBurrow You can do the same with Laravel's [helper functions for strings](http://laravel.com/docs/5.0/helpers#strings). e.g. `snake_case()` – lukasgeiter Feb 27 '15 at 17:02

1 Answers1

2

As I see it you basically have two options here:

1. Change the database to camelCase

snake_case is just Laravel's convention it not required to have your column names like that. So you could simply change the names to camelCase and set the $snakeAttributes option in your model(s) to false:

class MyModel extends Eloquent {
    public static $snakeAttributes = false;
}

Then you should be able to create() and get() your model with camelCase attribute names.


2. Override some methods

If you want to keep your db tables like they are you will have to override some methods in your model:

First, for array/JSON conversion:

public function toArray(){
    $array = parent::toArray();
    $renamed = [];
    foreach($array as $key => $value){
        $renamed[camel_case($key)] = $value;
    }
    return $renamed;
}

Then for setting and getting single attributes:

public function getAttribute($key){
    $key = snake_case($key);
    return parent::getAttribute($key);
}

public function setAttribute($key, $value){
    $key = snake_case($key);
    parent::setAttribute($key, $value);
}
Community
  • 1
  • 1
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270