Create aliases for columns in a table in Laravel

1

Is it possible to create aliases for the column names of a table in Laravel's Model? Example: I have a questao table with columns:

id
questao
disciplinas_id
serie_id
professor_id

It would be simpler if I could treat the columns by other names within the application. Call professor_id of prof , for example. I gave one searched but found nothing that would help me. Anyone know if Eloquent allows this? If so, how?

    
asked by anonymous 23.06.2017 / 13:13

1 answer

2

Easier than this, you can, at your Model , use accessor and mutator for set the shortcut. See the example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Questao extends Model
{
    public function getProfAttribute()
    {
        return $this->attributes['professor_id'];
    }
}

In this case, when accessing the value of $questao->prof , the getProfAttribute method is called by returning the value of the professor_id attribute. Now, to update the value through the shortcut, you need to set the mutator :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Questao extends Model
{
    public function setProfAttribute($value)
    {
        $this->attributes['professor_id'] = $value;
    }
}

What allows you to do something like $questao->prof = 3 .

    
23.06.2017 / 14:04