I'm using Laravel 5.6
. I have a users
table and firstname
and lastname
fields.
In my User
model I also have this function
public function name()
{
return $this->firstname . ' ' . $this->lastname;
}
And now in another controller, I want to create a dropdown menu with all the users. But I would like to display the name()
and not only the first/lastname.
I'm currently using this
$users = \App\User::pluck('lastname', 'id');
return view('myview', compact('MY_collection' , 'users'));
And in my view (with collective/html)
{!! Form::select('user', $users, isset($user) ? $MY_collection->user: null, ['class' => 'form-control']) !!}
Is is possible to use pluck with a method function ? Or should I do something else?
I am also aware of the accessor solution but I don't have a name
attribute in the database, so it is not working.
Accessors can be any name you choose, they just have to start with get
and end with Attribute
:
public function getNameAttribute() {
return $this->firstname . ' ' . $this->lastname;
}
$user->name
// this will give the result as above
public function getBlahBlahBlahAttribute() {
return $this->firstname . ' ' . $this->lastname;
}
$user->blah_blah_blah
Either of these should work with pluck.
User::get()->pluck('name');
$user->setAppends(['name']);
$user->pluck('name');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With