Reputation: 660
I've just started to create an application using the Laravel framework for the first time.
Eloquent seems to be a very powerful and code-saving tool, but I can't figure out how to use different attribute names in the model than in the database table.
Here my conflict:
Database: iddog, dtname, dtbirth, dtfoo, fimom, fidad
Attributes: id, name, birth, foo, mom, dad
Is there a possibility to do that in a model that extends from Eloquent in the Laravel framework? Naming attributes differently than the associated database fields?
Or isn't it cool anymore to call fields in a database table like I do here?
Thank's in advance!
Upvotes: 0
Views: 2729
Reputation: 41360
Now, with laravel 5.1 we call it Accessor instead of Getters & Setters.
So these days we have Accessor that create new attributes like this
public function getPlusFiveAttribute()
{
return $this->plus_five + 5;
}
Unfortunately if you already have a table field named 'plus_five ' - this Accessor will not work.
You need to go like this, it works:
public function getPlusFiveAttribute()
{
return $this->attributes['plus_five'] + 5;
}
Here is another approach that works:
public function getPlusFiveAttribute($value)
{
return $value + 5;
}
Upvotes: 1
Reputation: 60048
Why have different names for the database to your model?
Although you can do it - your just creating work for yourself, and introducing possible new bugs. Just use the database names.
If you must - check out Getters & Setters.
Upvotes: 0