Reputation: 4987
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.
Upvotes: 28
Views: 37935
Reputation: 11042
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');
Upvotes: 58
Reputation: 1763
if your column is nullable then you should try this
convert the NULL
values with empty string by COALESCE
$ProjectManagers = Employees::select(
DB::raw("CONCAT(COALESCE(`first_name`,''),' ',COALESCE(`last_name`,'')) AS name"),'id')
->where('designation', 1)
->pluck('name', 'id')
->toArray();
Upvotes: 4
Reputation: 2652
I also faced a problem like that with join query here is the solution of my problem
$studentDegree = Student::leftJoin('degree','degree.student_id','=','student.id')
->select(
DB::raw("CONCAT(student.name,'-',degree.name) AS name_degree"),
'student.id'
)->lists('name_degree','id');
Upvotes: 3
Reputation: 902
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');
Upvotes: 62