Reputation: 422
I am using laravel and I want to add dynamic custom attribute in controller
I know there is a way like this
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
now you can get full name as:
$user = User::find(1);
$user->full_name;
but it is in Model I want to declare custom att in controller is it possible?
Upvotes: 0
Views: 2646
Reputation: 1085
Why not in model? Eloquent has a great feature called “Accessors”. The feature allows you to add custom fields to models that don’t exist on the model or in the table.
function getFullNameAttribute() {
return sprintf('%s %s', $this->first_name, $this->last_name);
}
Now you have access to a full_name attribute on the model, same as you mentioned:
$user = User::find(1);
$user->full_name;
Upvotes: 2