Pablo
Pablo

Reputation: 1435

Query single column and return comma separated Laravel PHP

 $getStrain = DB::connection('mysql')->select('
    SELECT
        
       b.yeast_class_id
    FROM 
        yeast_classes AS a
    LEFT JOIN
        classes_per_yeast AS b 
    ON 
        a.id = b.yeast_class_id
    WHERE
        b.yeast_id = "'.$id.'"
    GROUP BY
        b.yeast_class_id
');

dd($getStrain);

and it returns something like this

enter image description here

But what I want to do is get a response something like this

1,4,5,6,7

where all yeast_class_id will be combined together

Upvotes: 1

Views: 1308

Answers (2)

lagbox
lagbox

Reputation: 50501

From that array of objects you have you could pluck the field you want from them into an array:

Illuminate\Support\Arr::pluck($getStrain, 'yeast_class_id')

Or put the array into a Collection and use the pluck method on the Collection:

collect($getStrain)->pluck('yeast_class_id')->all()

If you want a comma separated string of the list:

collect($getStrain)->pluck('yeast_class_id')->join(',')

Laravel 8.x Docs - Helpers - Array & Objects - Arr::pluck

Laravel 8.x Docs - Helpers - Miscellaneous - collect

Laravel 8.x Docs - Collections - Available Methods - pluck

Laravel 8.x Docs - Collections - Available Methods - all

Laravel 8.x Docs - Collections - Available Methods - join

Upvotes: 4

bhucho
bhucho

Reputation: 3420

Check the helper values()

$getStrainValues = $getStrain->values();

Upvotes: 1

Related Questions