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

Daniel-Pablo's avatar

Laravel Query ( join,group By and show from more to less count of rows)

Hello, this is the progress that I have taken so far, I have managed to join and group the data but I am missing that data to show me the groups from largest to smallest, could someone help me or guide me on how to do it?

DB::table('scores')
                ->leftJoin('likes', 'scores.id', '=', 'likes.score_id')
                ->get()
                ->groupBy('score_id')

Result: (I join and group the data but now i need to show it from the grup that have more to less in this case first the one that have 8 and then the other 4 )

Illuminate\Support\Collection {#1479 ▼
  #items: array:2 [▼
    4 => Illuminate\Support\Collection {#1561 ▼
      #items: array:4 [▼
        0 => {#1552 ▶}
        1 => {#1503 ▶}
        2 => {#1588 ▶}
        3 => {#1500 ▶}
      ]
    }
    1 => Illuminate\Support\Collection {#1538 ▼
      #items: array:8 [▼
        0 => {#1564 ▶}
        1 => {#1486 ▶}
        2 => {#1581 ▶}
        3 => {#1579 ▶}
        4 => {#1562 ▶}
        5 => {#1573 ▶}
        6 => {#1574 ▶}
        7 => {#1575 ▶}
      ]
    }
  ]
}
0 likes
6 replies
alexios's avatar

You can sort your collection by number of items of previously grouped collections:

DB::table('scores')
  ->leftJoin('likes', 'scores.id', '=', 'likes.score_id')
  ->get()
  ->groupBy('score_id')
  ->sortByDesc(function ($scores, $key) {
      return $scores->count();
  });
Daniel-Pablo's avatar

I really appreciate your help but could you tell me how I do the foreach to visualize this data?

alexios's avatar

First check if result of this query is correct, as you said from more to less count of rows. You have two grouped collections in collection, so you need to first do foreach on the main one and then of his children (groups).

// $scores = your query's result

In Blade:

@foreach ($scores as $group)
    @foreach ($group as $score)
        {{ $score->id }}
    @endforeach
@endforeach

I don't know exactly what you want to achieve - change your results or try to show the current data in view?

MichalOravec's avatar

Why not to use Eloquent?

Score::withCount('likes')->orderByDesc('likes_count')->get();
Daniel-Pablo's avatar

I get this far, how i connect your idea to this?

Score::leftJoin('likes', 'scores.id', '=', 'likes.score_id')
                ->get()

Please or to participate in this conversation.