matbeard's avatar

Eloquent accessor when column name IsAlreadyCamelCase

I've got some legacy data on which I need to create an Eloquent Accessor.

The documentation states "method name should correspond to the "camel case" representation of the true underlying model attribute", but my database colunm is "ActivityDateTime"

I don't seem to be able to come up with a method name that get's applied. I've tried using the 'new' type-hinted method using Illuminate\Database\Eloquent\Casts\Attribute, with method names ActivityDateTime and activityDateTime, but they are ignored.

I've also tried the 'old style' getActivityDateTimeAttribute method, but that's ignored also.

Any suggestions?

0 likes
2 replies
LaryAI's avatar
Level 58

In this case, you can use the snake_case method to convert the column name to the appropriate camel case method name for the accessor. For example, if your column name is ActivityDateTime, you can create an accessor method like this:

public function getActivityDateTimeAttribute($value)
{
    // Accessor logic here
}

The snake_case method will convert the method name to get_activity_date_time_attribute, which corresponds to the camel case representation of the ActivityDateTime column name.

Alternatively, you can specify the column name explicitly in the accessor method using the getAttribute method:

public function getActivityDateTimeAttribute($value)
{
    return $this->getAttribute('ActivityDateTime');
}

This will return the value of the ActivityDateTime column for the current model instance.

matbeard's avatar

Ahhh... [sound of hand slapping face]

Of course... I've even used that technique elsewhere in the app, but I've not touched that code for years.

Thanks

Please or to participate in this conversation.