Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gse.amit's avatar

How to process the resultset of a raw query in Laravel

I have a helper function which takes category as input and returns with all items for that category in comma separated string.

public static function getItemsByCategory($categoryId){
        $categoryString="";
        $query = DB::table('items');
        $query->select(DB::raw('item_code'))
            ->where('category', '=', $categoryId)->get();

        foreach($query as $result){
            $categoryString= $categoryString.','.$result->item_code; 
        }    
        dd($categoryString);
        return $categoryString; // output should be like "item1, item2, item3"
    }

Also I am not being able to print out the item code using dd(). It says, "Undefined property: Illuminate\Database\MySqlConnection::$item_code"

Thanks for any help!

0 likes
4 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you need to assign the values to a variable

$categories = $query->select(DB::raw('item_code'))
        ->where('category', '=', $categoryId)->get();

then manipulate categories

eloquent way

public static function getItemsByCategory($categoryId)
{
    return implode(',', Item::where('category',$categoryId)-pluck('item_code'));
}
1 like
gse.amit's avatar

Hi Snapey, Your suggestion to assign it to a separate variable did the trick. Thanks a ton for your help!

gse.amit's avatar

Well, I have not removed DB::raw() yet. This is how I managed so far.

public static function getItemsByCategory($category){
        //DB::enableQueryLog();
        $outputString="";
        $sites = DB::table('items')
                    ->select(DB::raw('item_code'))
                    ->where('category', '=', $category)
                    ->get();
        //dd(DB::getQueryLog());        
        foreach($items as $key=>$value){
            if($key==0)
                $outputString= '"'.$value->item_code.'"';
            else    
                $outputString= $outputString.', "'.$value->item_code.'"';
        }
        //dd($outputString);
        return $outputString;
    }

Thanks again!

Please or to participate in this conversation.