Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel use of concat with pluck method

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.

like image 986
Punit Gajjar Avatar asked Sep 05 '25 09:09

Punit Gajjar


2 Answers

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');
like image 180
Blaž Oražem Avatar answered Sep 07 '25 23:09

Blaž Oražem


Try changing the eloquent query to:

$ProjectManagers = Employees::select(
            DB::raw("CONCAT(first_name,' ',last_name) AS name"), 'id')
            ->where('designation', 1)
            ->pluck('name', 'id');
like image 44
martincarlin87 Avatar answered Sep 07 '25 22:09

martincarlin87