Ahmad Elkenany
Ahmad Elkenany

Reputation: 585

laravel query builder (GROUP CONCAT) error

I have a collection of user skills but i need is to get only skills as an array i tried this

$builder->where('job_id', $value)
->join('users', 'job_applicants.user_id', '=', 'users.id')
->join('user_skills', 'users.id', '=', 'user_skills.user_id', function ($join){
    $join->selectRaw("GROUP_CONCAT(user_skills.skill, ', ')");
})
->groupBy('job_applicants.job_id')
->get();

The exception message : Object of class Closure could not be converted to string

Upvotes: 0

Views: 234

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

The join closure should be the first and only argument after the table name.

->join('user_skills', function ($join) {
    $join->on('users.id', '=', 'user_skills.user_id')
         ->selectRaw("GROUP_CONCAT(user_skills.skill, ', ')");
});

However, a selectRaw inside the join closure doesn't make a whole lot of sense. Logically, this isn't where you select data. You've joined the table, your select statement belongs in the main query, it doesn't belong contained within the join, like so:

$builder->selectRaw("job_applicants.*, GROUP_CONCAT(user_skills.skill, ', ')")
    ->where('job_id', $value)
    ->join('users', 'job_applicants.user_id', '=', 'users.id')
    ->join('user_skills', 'users.id', '=', 'user_skills.user_id')
    ->groupBy('job_applicants.job_id')
    ->get();

Upvotes: 2

Related Questions