This is what you need: http://laravel.com/docs/5.0/eloquent#accessors-and-mutators
getAgeAttribute($value)
{
return $this->attributes['age_of_me'];
}
Now you can do this on your model
$customer->age;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey everybody,
I asked my self and did't find anything about this topic, so I will try it in the best Laravel community all over the world - here at Laracasts.
Did you guys ever tried to alias Eloquent model columns? I'll give you an example: Let's say we have a table called "customers" and that table has three columns: "customer_name", "age_of_me", ''current_status".
I could create an Eloquent model that looks like this:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model {
protected $fillable = [];
public $timestamps = false;
}
When I like to get all customers using return Customer::all(); I'll get a Collection containing all of those customers with the corresponding fields "customer_name", "age_of_me", ''current_status".
But now assume, that I don't like these field names and I can't rename them because other Enterprise solutions are using them. As a go(o)d developer I wanna have a clean and easy to understand codebase, so I like to get the field "name", "age", "status" in return.
Do you know any possibility to assume that, but without using the query builder and doing things like select customer_name as name ... from? A property like protected $aliases would be nice. What do ya think?
@bart If you want to simply rename the columns and use the aliases in toArray representation, use this mix:
$maps = ['bad_number_column' => 'number', 'bad_date_column' => 'date'];
$hidden = ['bad_number_column', 'bad_date_column'];
$appends = ['number', 'date'];
then you will get:
// dd(Customer::all()->first()->toArray())
[
'number' => 123,
'date' => '2015-05-25 18:33:00',
...
]
I assume this is what you wanted. Let me know otherwise.
Please or to participate in this conversation.