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

monstajamss's avatar

Get specific values from SQL Query

I am trying to get the values of koh, kih etc specifically in this SQL Query below

$afterhours = $this->electricityConnections->select(\DB::raw('SUM(kwh_used_out_of_hours) as koh'), 
        (\DB::raw('SUM(kwh_used_in_hours) as kih')), (\DB::raw('SUM(cost_out_of_hours) as coh')), 
        (\DB::raw('SUM(cost_in_hours) as cih')))
        ->from('after_hours_yesterday_category')
        ->where('category_id', '=', 11)
        ->where('building_id', '=', 52)
        ->get();

       return $afterhours;

I did this in other to get them

$afterhours = $this->electricityConnections->select(\DB::raw('SUM(kwh_used_out_of_hours) as koh'), 
        (\DB::raw('SUM(kwh_used_in_hours) as kih')), (\DB::raw('SUM(cost_out_of_hours) as coh')), 
        (\DB::raw('SUM(cost_in_hours) as cih')))
        ->from('after_hours_yesterday_category')
        ->where('category_id', '=', 11)
        ->where('building_id', '=', 52)
        ->get();

       dd($afterhours->koh);

and i got this error "message": "Property [koh] does not exist on this collection instance.", .

What am i doing wrong?

When i dd($afterhours) only i get this

#attributes: array:4 [
        "koh" => "440.59"
        "kih" => "773.74"
        "coh" => "67.64"
        "cih" => "129.52"
      ]
0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You are using get() so you get multiple rows (a collection). If you only want one row, use first()

        ->where('category_id', '=', 11)
        ->where('building_id', '=', 52)
        ->first();

Or use foreach

foreach ($afterhours as $a) {
    dump($a->koh);
} 

Please or to participate in this conversation.