I need to populate a blade format tag.
I\'m aware of the Model::pluck(\'column1\', \'column2\')
method to populate a select tag.
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);
Another simple way:
return User::select(DB::raw('CONCAT(first_name, " - ", last_name) AS full_name, id'))
->pluck('full_name', 'id');
Just so people who come here know, the pluck method returns an object, and if you want to pluck multiple columns and return an array at the same time without using the toArray
method, you could just pass the names of the column to the all()
function, and it will return the wanted columns as an array.
YourModelName::all('id', 'name');
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.
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];
})