Using an accessor or mutator if the column has 2 consecutive underscores

Viewed 685

I have a column in my database Started_Trading__c. I'm struggling to use an accessor for this field. So far I have tried the following with no luck.

public function getStartedTrading_cAttribute()

public function getStartedTrading__cAttribute()

public function getStarted_Trading__cAttribute()

public function getStarted_Trading_cAttribute()

What would be a valid way to get an accessor working with this type of column name which has 2 consecutive underscores __c.

Unfortunately I have no control over the database column names so ideally i'd like to get this to work.

Thanks

1 Answers

Laravel uses the Str::class to process strings, for the name of the mutator it uses the method camel.

The following strings will all result in getStartedTradingCAttribute

Str::camel('get started trading c attribute')
Str::camel('get started_trading_c attribute')
Str::camel('           get started___trading__________c attribute')
Str::camel('get____started  __  trading   __c  ___attribute')

The method you need to declare is getStartedTradingCAttribute()

For more details (methods are simplyfied)

public static function camel($value)
{
    return lcfirst(static::studly($value));
}

public static function studly($value)
{
    $key = $value;

    $value = ucwords(str_replace(['-', '_'], ' ', $value));

    return str_replace(' ', '', $value);
}

As you can see, all _(underscore) are replaced with (space) then nothing in studly()

Related