Laravel: Model’s column alias
Now this is a story all about how
My life got flipped turned upside down…
I always wanted to start with these lyrics.
Anyway that’s not the reason why I’m here.
THE PROBLEM
I’m here ’cause I’m new with Laravel and, after less than a month developing a new portal, I found that I need to change the name of a couple of columns of a model, without altering the mysql’s table. I can use the alias in each query, but it’s a little tricky. I need something more effective.
THE SOLUTION
After some research (thank god for stack and laracast) I found that there’s the possibilities to map fields inside any model. Didn’t find anything in the official docs, but it can be that I missed it.
However it is quite simple: you have to set the protected $maps property as an array with the db columns as key and the new keys as values, just like this:
protected $maps = [
'dbCol1' => 'coolName1',
'dbCol2' => 'coolName2'
];
After that you need to append those keys to the model using the protected property $append
protected $append = ['coolName1', 'coolName2'];
If you try to run a query now, you’ll get an exception cause Laravel also needs a public “mapper method” for your properties. So, just add something like this:
public function getCoolName1Attribute()
{
return $this->attributes['dbCol1'];
}public function getCoolName2Attribute()
{
return $this->attributes['dbCol2'];
}
If you want to hide your old columns in the model you can use the property $hidden:
protected $hidden = ['dbCol1', 'dbCol2'];
CONCLUSION
So, it works, and it works flawlessly!
That’s it!
Pretty awsome, isn’t it?
The only problem is that if you build a query with your model and want to select columns that are in the maps, you need to use the original name, not the new one.
Thanks for reading :)