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);
}
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;
}
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