Neha
Neha

Reputation: 2261

How to set or get attributes in Laravel model for fields with Capital letters?

If I have fields in my database like this: date_install, then I can set an attribute function named :

Field name: date_install:

public function setDateInstallAttribute($date)
{
        //code
}

But I need to set an attribute for a field starting with capital letter:

Field name : DateInstall.

What will be the name of function? setDateInstallAttribute is not working.

Upvotes: 0

Views: 1318

Answers (2)

ujiriukiri
ujiriukiri

Reputation: 306

The convention although not set in stone is to use snake case (snake_case) when naming DB fields. In Laravel, this is paramount because the framework depends heavy on snake_case and studlyCase especially when dealing with Models (table names, foreign keys, accessors and mutators etc). In this case the mutator has to follow the pattern setFooAttribute where Foo is the "studly" cased name of the column (snake_case) you wish to access.

Upvotes: 1

Gert de Pagter
Gert de Pagter

Reputation: 141

Laravel looks for mutators like these by capitalizing the first word. If provided with already capitalized attributes it should work correctly.

So if your field is named DateInstall then setDateInstallAttribute should be a valid method name.

Upvotes: 0

Related Questions