Laravel use of concat with pluck method

Punit Gajjar picture Punit Gajjar · Oct 19, 2016 · Viewed 26.9k times · Source

I am using Laravel.5.3 and below is my query

$ProjectManagers = Employees::where("designation" , 1)
->pluck(DB::raw('CONCAT(first_name," ",last_name) AS name'),'id');

which throws an error that

Illegal offset type in isset or empty

May i know if this is the correct method ?

if i dont use contact and use like

$ProjectManagers = Employees::where("designation" , 1)->pluck('first_name','id');

which is working correct and giving me result

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [8] => Punit
        )

)

Expected Result :

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [8] => Punit Gajjar
        )

)

where first name and last name are concatenated.

Answer

Blaž Oražem picture Blaž Oražem · Aug 18, 2017

The most elegant solution is to create an accessor.

Open your Employees class (model) and add an accessor function:

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

After that, just simply use:

$ProjectManagers = Employees::where('designation', 1)->get()->pluck('full_name', 'id');