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

pordonez's avatar

Laravel query

Hello guys, i have a record on my database something like this

--------------------
Name|Count
--------------------
Item 1 | 5
Item 2 | 10
Item 3 | 4
Item 1 |4
Item 3 | 5
--------------------

now what i want to do with my query is this

Item 1 - 9
Item 2 - 10
Item 3 - 9

can anyone help me please?.

0 likes
4 replies
Sergiu17's avatar
DB::table('table')
    ->select('item', DB::raw('count(*) as Total'))
    ->groupBy('item')
    ->get();
Model::groupBy('item')
->selectRaw('count(*) as Total, item')
->get();

Does some this this example work?)

1 like
pordonez's avatar

@SERGIU17 - the count only giving me the total count of the item. like this

Item 1 - 2
Item 2 - 1
Item 3 - 2
Sergiu17's avatar

@PORDONEZ - Oh, sorry, use - SUM(column_name), instead of COUNT(*)..

Model::groupBy('item')
->selectRaw('SUM(count) as Total, item')
->get();
toby's avatar
toby
Best Answer
Level 31

Try to use sum() instead of count()

DB::table('table')
    ->select('item', DB::raw('sum(count) as Total'))
    ->groupBy('item')
    ->get();

Please or to participate in this conversation.