Laravel ::pluck multiple columns

2020-08-10 06:46发布

问题:

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 ?

回答1:

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.



回答2:

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


回答3:

Model results retrieved by the get() method are just children of the regular Support-Collection class, so you actually get access to all the same goodies. Try this:

$eloquentCollection = app(YourModel::class)
    ->where('field', 'value')
    ->get(['id', 'column_1', 'column_2']);

$mapped = $eloquentCollection->mapWithKeys(function (YourModel $model) {
    return [$model->id => $model->column_1 . $model->column_2];
})


回答4:

Another simple way:

    return User::select(DB::raw('CONCAT(first_name, " - ", last_name) AS full_name, id'))
           ->pluck('full_name', 'id');