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');
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.
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.
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