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 ?
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();
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.
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();
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.
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.
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);
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