Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel pluck with custom method from model

Tags:

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.

like image 687
Atnaize Avatar asked Jun 29 '18 10:06

Atnaize


1 Answers

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');
like image 51
Brian Lee Avatar answered Oct 04 '22 17:10

Brian Lee