Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ::pluck multiple columns

I need to populate a blade format <select> tag.

I'm aware of the Model::pluck('column1', 'column2') method to populate a select tag.

But in my case, I have to concatenate two columns , and get the id. something like

Model::pluck('column_1 && column_2', 'id')

Is it possible like that ? If yes, what would be the proper syntax?

If not, what would be the best alternative then ?

like image 513
Lucentyr Avatar asked Mar 09 '18 07:03

Lucentyr


People also ask

How can I pluck two fields in laravel?

You should use select() with get() and then later on modify the object as you need. So instead of: ->pluck('region','district'); use: ->select('region','district')->get();

What is Pluck () in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

How do you pluck a relationship in laravel?

You can achieve it by using join() & pluck() like this: $s = Seller::join('users', 'sellers. user_id', '=', 'users.id') ->pluck('sellers.id', 'users.id') ->all();

What is difference between Pluck and select in laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.


2 Answers

Best solution is to create accessor function into your model, let's assume if you want to get full name then you can do like this.

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

and you can easily get full name.

$users = User::where('id', 1)->get()->pluck('full_name', 'id');

Eloquent will call getFullNameAttribute function and get concatenated value.

like image 177
Faraz Irfan Avatar answered Oct 14 '22 02:10

Faraz Irfan


You could use selectRaw():

Model::selectRaw("CONCAT ('column1', 'column2') as columns, id")->pluck('columns', 'id');

Or you could do this manually:

$collection = Model::get(['column1', 'column2', 'id']);
foreach ($collection as $item) {
    $plucked[$item->id] = $item->column1 . $item->column2;
}
dd($plucked);
like image 6
Alexey Mezenin Avatar answered Oct 14 '22 04:10

Alexey Mezenin