Create alias for columns of a table in Laravel

Asked

Viewed 186 times

1

Is it possible to create alias for the columns name of a table in using the Laravel Model? Example: I have a table questao with the 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. Calling professor_id of prof, for example. I did some research but found nothing to help me. Does anyone know if Eloquent allows it? If so, how to do it?

  • From the examples I saw when searching, it is possible to do this using this solution - https://github.com/jarektkaczyk/eloquence/wiki/Mappable

1 answer

2


Easier than that, you can, in your Model, utilise accessor and mutator to define 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 method getProfAttribute is called by returning the value of the attribute professor_id. Already, to update the value through the shortcut, you need to define the mutator:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

  • Perfect! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.