alexleonard
alexleonard

Reputation: 1314

Is it possible to still use Laravel 5 Accessors to access multiple attributes

Perhaps I'm missing something very obvious here but if I do:

public function getName()
{
    return $this->first_name . ' ' . $this->last_name;
}

and then in my view do

$user->name

I get nothing back. But if I run

$user->getName()

Then it works as expected. Is it not possible to create an accessor that accesses multiple attributes?

Upvotes: 0

Views: 1745

Answers (2)

The Alpha
The Alpha

Reputation: 146191

You should use something like this in your User model as an accesor:

public function getNameAttribute($value)
{
    return $this->first_name . ' ' . $this->last_name;
}

So you can use $user->name property. The name format is getPropertyAttribute.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Your function should should have name getNameAttribute and not getName to make it work as accessor (docs reference) and use $user->name to access result of your accessor. Now you created standard function and if you want to run it you need to run function as in all standard PHP functions.

Upvotes: 3

Related Questions