Bedouin
Bedouin

Reputation: 83

How to merge values of collection using pluck function?

I use the pluck() function to get output collection with key, value:

$work_types = Work::orderBy('name')->get()->pluck('name', 'id');

Output is:

{
  0 => "Name1",
  1 => "Name2",
  2 => "Name3
}

How can I merge value name with value id that to get the following object:

 {
      0 => "0 -Name1",
      1 => "1 - Name2",
      2 => "2 - Name3
    }

Upvotes: 3

Views: 5595

Answers (4)

thewebcompiler
thewebcompiler

Reputation: 89

Merge ****FirstName** and **LastName**** From Database:

'clients' => Client::select('id', DB::raw("concat(first_name, '   ',last_name) as f_l"))

                ->orderBy('id','desc')

                ->pluck('f_l', 'id')

                ->prepend('Select Clients.....',''),

Upvotes: 0

Amit Gupta
Amit Gupta

Reputation: 17658

You can use select() function with DB::raw() fuction to this as:

$work_types = Work::select('id', DB::raw("concat(id, ' - ',name) as id_name"))
                ->orderBy('name')
                ->pluck('id_name', 'id')

You don't need to get all the columns and then do pluck. You can directly pluck from the database.

Upvotes: 1

Rwd
Rwd

Reputation: 35170

You could use map:

$work_types = Work::orderBy('name')->pluck('name', 'id')
    ->map(function ($item, $key) {
        return "$key - $item";
    });

https://laravel.com/docs/5.3/collections#method-map

Hope this helps!

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

The Laravel way is to create an accessor:

public function getIdNameAttribute($value)
{
    return $this->id.' - '.$this->name;
}

And then use it:

$work_types = Work::orderBy('name')->pluck('id_name', 'id');

Upvotes: 6

Related Questions