Laravel 4 Eloquent Column Alias

Lpc_dark picture Lpc_dark · Jun 18, 2013 · Viewed 8.7k times · Source

What i am trying to achieve is in my database i have a table named channel i am using laravel's eloquent class to access these the properties from the table The problem that i am facing is that

the table name is column and the column name is channel

so when accessing that property looks like this.

User::find(1)->channel->channel

How can i modify this to say

User::find(1)->channel->name

We cannot change the table name in the database.

Options i have thought of:

1)Create views for tables that need columns changed. Too messy...

2)Use column alias.... laravel documentation...sigh.. no clue how?

3)Use a property set with the create_function that would call this->channel but i am pretty sure it won't work because laravel is using dynamic properties. and when it's fill out in the array im pretty sure it changes it to the name of the column.

I could in my belongs_to/hasOne/hasMany function change the property to the alias of the name i want to use so that later on i can change it. i dunno how well that would work..

any thoughts? much appreciated

Answer

Alexandre Danault picture Alexandre Danault · Jun 19, 2013

You could probably do it easily with Accessors / Mutators.

class Channel extends Eloquent {

    public function getNameAttribute()
    {
        return $this->attributes['channel'];
    }

    public function setNameAttribute($value)
    {
        $this->attributes['channel'] = $value;
    }

}

Reference