Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force laravel to use camelCase for column names

Larvel uses snake_case for table columns name. How to overwrite this assumption in a way the following getter works?

public function getFooBarAttribute()
{
    return json_decode($this->attributes['fooBar'], true);
}
like image 798
Handsome Nerd Avatar asked Feb 14 '16 09:02

Handsome Nerd


1 Answers

I need to first caveat this answer with the following: I haven't tested this code; secondly I have never had a requirement to use this.

With that said, there is a static property available on eloquent models:

/**
 * Indicates whether attributes are snake cased on arrays.
 *
 * @var bool
 */
public static $snakeAttributes = true;

By switching this to false, you turn off snake casing of attribute names AND relationship names on the model. This should have the desired outcome you are looking for.

If you're interested the source code for a model has a method cacheMutatedAttributes that runs a regular expression across the attributes to check whether any mutations are present, if they are the match is run through the following snippet.

if (static::$snakeAttributes) {
    $match = Str::snake($match);
}

As this is a static property, you can globally change this for all models by changing the static value on the model itself. Otherwise you can make this change on a per model basis by overwriting the static in each model you need it. To change globally, you can add something like this to your AppServiceProvider:

public function boot()
{
    \Illuminate\Database\Eloquent\Model::$snakeAttributes = false;
}
like image 188
David Barker Avatar answered Oct 31 '22 16:10

David Barker