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

pordonez's avatar

Laravel distinct query

I have the following data

item 1 - 5
item 2 - 7
item 3 - 4
item 1 - 4
item 2 - 20

what query do i need to do to display this kind of result

item 1 - 5
item 2 - 20
item 3 - 4

names should be distinct and get the highest value.

0 likes
5 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Not knowing your column names nor the model, so give this a try and let me know:

// replace name and count with your column names
Model::select('name', \DB::raw('max(count)'))->groupBy('name')->get();
1 like
pordonez's avatar

@NAKOV - the column names are name, final_price, and i tried your query the result is empty.

pordonez's avatar

@NAKOV - it worked, the only problem is you forgot to use

DB::raw('max(count) as price')

thanks for the idea @nak

Nakov's avatar

So you've tried this:

YOUR_MODEL_NAME_HERE::select('name', \DB::raw('max(final_price)'))->groupBy('name')->get();

Please or to participate in this conversation.