Kuxa Kuxa - 3 months ago 6
PHP Question

Laravel - add model property on DB select

I am currently developing a website using Laravel 5.2 and I ran into this problem many times now, so I decided to ask for help.

I am going to give you a simple example of my problem.

Let's say I have a DB of clients. There are colums id, name, surname etc. And I want to get client's full name in my Blade view.

Currently, I would do something like this

class Client extends Model {
public function fullName() {
return $this->name . " " . $this->surname;
}
}


And then in my view I would do
$client->fullName()
.

It works, but I think it is not the right approach. I think it would be better if the full name was stored as object property and not method.

Is there any way I could do this? I am pretty sure there must be a way how to do this in Laravel because imho this problem is quite common, but my problem is I don't know what should I google.

Answer

you may define an accessor for that like so

public function getFullNameAttribute()
{
    return $this->name . " " . $this->surname;
}

and add that attribute to $appends property to be automatically included in both the model's array and JSON forms

protected $appends = ['full_name'];

now you can access it as a property $user->full_name;

Laravel Accessors & Mutators

Comments