Laravel - muscular attribute

I ran into a problem, and this is really a minor inconvenience, but ...

Essentially, I need an associative array for the select box. This is usually achieved using the pluck() function.

The problem is that the attribute that I want to use as "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 in the model will include this field when casting the model to an array, however, this doesn't seem to work with pluck()

Is there an easy way to achieve what you want? Function or declaration I'm missing? Anything more eloquent than looping through a collection manually and creating your own associated array?

Refresh

I am an idiot. I passed an array to collect instead of two parameters. Obviously pluck uses the $appends attribute. Please note that this only works when working with collections:

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

NOT query builder

 $queryBuilder->pluck('mutatedValue', 'id'); 
+6
source share
3 answers

You can dynamically add an attribute to objects in your collection:

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

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

+4
source

I was looking for the answer to this question and got a different result, so I decided to share with him.

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

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

+10
source

You can request with eloquent and use

 $limited_select = User::all(['id', 'first_name', 'last_name']); $limited_select = array_flip($limited_select); 

I assumed that you wanted to prevent select * when possible.

by generating a selection, you can do something like this in the blade:

 <select> @foreach($limited_select as $user) <option value={{$user->id}}> {{$user->getNameAttribute() }} </option> @endforeach </select> 

This will work because getNameAttribute() inside your User Model wil acts as an accessor.

The second option may be to use a raw request with concat, but I think the eloquent way is more elegant.

+1
source

Source: https://habr.com/ru/post/1263893/


All Articles