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

grigelionis's avatar

Laravel Query Builder - how to select pairs of items?

Hi guys, I will try to explain what i want to achieve by simple example.

I have one table with following data:

id, domain, clicks, url 1, example.com, 54, http://example.com/link1 2, oranges.com, 13, http://oranges.com/link1 3, example.com, 10, http://example.com/link2 4, apples.com, 3, http://apples.com/link1 5, apples.com, 7, http://apples.com/link2 6, crocs.com, 10, http://crocs.com/link1 7, oranges.com, 88, http://oranges.com/link2 8, example.com, 12, http://example.com/link3 9, example.com, 7, http://example.com/link4 10, apples.com, 9, http://apples.com/link3 ......

My aim is to select pairs (two or one) of domains who have most clicks. So after querying the results of above (example) table could look following:

results, selected ids: 1, 8 (<-- example.com) 2, 7 (<-- oranges.com) 5, 10 (<-- apples.com) 6 (<-- crocs.com)

How to do that with Laravel Query Builder? Or it will need to manipulation in plain php level at controller?

Thanks!

0 likes
2 replies
Punksolid's avatar

Hi @grigelionis I think I didn't understand what do you mean with pairs of domains. If you want to retrieve the 2 most clicked domains is something like this

Link::orderBy('clicks', 'DESC')->take(2)->get();

Is that what you want? Or do you want all registries in some kind of order?

grigelionis's avatar

@PUNKSOLID - Thanks for the prompt answer.

Sorry for unclearness of question. I want to retrieve two results for each domain.

Backing to my example above, there will be 7 results:

two for domain - example.com, two for oranges.com, two for apples.com and one for crocs.com

Please or to participate in this conversation.