0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you sooo much! This is gonna make my life so easier :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.