With:
Users::all();
I have all the users according to my db columns. In my case, I have
id|name|first_name
But I need to have the name
and last_name
in the same key.
Is there any option of Laravel 5.6 to create on the fly another column to that Users collection?
Something like:
Users::createColumn('fullname', ['name, 'last_name');
or something like that.
EDIT:
Right now I'm doing this:
$users = User::all();
$users->map(function ($fullname) {
$fullname['fullname'] = $fullname->name . ' ' . $fullname->last_name;
return $fullname;
});
Laravel's Accessors & Mutators is what you're looking for.
In your User.php model:
/**
* Get the user's full name.
*
* @return string
*/
public function getFullnameAttribute()
{
return "{$this->name} {$this->last_name}";
}
Then, you access it like so:
$user->fullname
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.