0

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!

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

These are accessors. And in your first example it would be better to be $this->attributes['plus_five'] + 5.
Thanks!. $this->attributes['plus_five'] + 5 - worked and it is a new syntax. Great. And it is accessors, not mutators, you are right. I changed the answer. Thanks again.
0

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.

1 Comment

I always use a specific name convention when modeling database tables which I don't want in my models. I'll rename the database table. Ty for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.