Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - pluck mutated attribute

I have run into an issue, and it is really only a minor inconvenience, but...

Basically what I need is an associative array for a select box. Normally, this would be achieved using the pluck() function.

The problem is, the attribute that I want to use as the 'text' does not actually exist in the database, it is a mutator that combines two fields into one.

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

I know that adding the 'name' field to the $appends array on the model will include that field when casting the model to array, however this does not seem to work with pluck()

Is there a simple way to achieve want I want? Function or declaration I'm missing? Anything more eloquent than manually looping over the collection and creating my own associate array?

Update

I'm an idiot. I was passing an array to pluck instead of two parameters. Apparently pluck does utilize the $appends attribute. Note, this only works when working with collections:

$collection->pluck('mutatedValue', 'key');

NOT the query builder

$queryBuilder->pluck('mutatedValue', 'id');
like image 835
D.Meganoski Avatar asked Feb 06 '17 20:02

D.Meganoski


2 Answers

I was looking for an answer to this and ended up with a different result so I thought I'd share.

User::get()->pluck('name');

If you get the object first, your mutated attribute will be accessible.

like image 50
Zach Chisholm Avatar answered Sep 20 '22 02:09

Zach Chisholm


You can dynamically append the attribute to the objects in your collection:

$users->each(function ($model) { $model->setAppends(['name']); });
$users->pluck('name');

This has the nice advantage of not requiring 'name' always be part of your array data, while allowing your collection to use name just in time.

like image 34
bishop Avatar answered Sep 20 '22 02:09

bishop