How to pluck multiple columns in Laravel

Hasnain Kahn picture Hasnain Kahn · May 2, 2019 · Viewed 7.3k times · Source

I want to get a student's full name, but in my database, I have two different columns: first_name and last_name. I want to get both of these columns at the same time.

Controller

public function getStudentName($id) 
{
    $students = DB::table("students")->where("students_class_id", $id)
        ->pluck("first_name", "id");

    return json_encode($students);
}

Answer

Zakaria Acharki picture Zakaria Acharki · May 2, 2019

Create custom accessor in your eloquent model like :

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

Then use it in the query like :

$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");

Try it with eloquent like :

Student::where("students_class_id",$id)->pluck("full_name","id")->toArray();