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

jstoone's avatar

Get most active users

I'm building a service where users can upload three types of content.

  • Snippets
  • Files
  • Urls (shortened)

All three tables has a FK user_id, and relations defined in the model. A User has many snippets, files and urls. And they belong to one user.

Now I've come to the part where I have to create an administration panel where I can get an overview of things. And I'll start with getting three lists:

  1. A list of users who created the most snippets
  2. A list of users who created the most files
  3. [...] the most shortened urls

Tech time

As of right now I've got something along the lines of:

$snippetsUsers = User::select(['users.*', \DB::raw('count(snippets.id) as snippetscount')])
    ->join('snippets', 'users.id', '=', 'snippets.user_id')
    ->groupBy('users.id')
    ->orderBy('snippetscount', 'desc')
    ->limit(15)
    ->get();

As of right now, this outputs a few diffrent results every time I reload, so I assume it's not correct since there is no activity on my local site.

A little extra

The above approach is using the Query Builder. But I was thinking if there is a way to use the magnificent power of eloquent? Here is what I was thinking (this code is not functional):

$snippetsUsers = User::with('snippets')
    ->orderBy(\DB::raw('COUNT(snippets.id)'))
    ->get();

Any ideas are welcome!

0 likes
2 replies
davidfaux's avatar
Level 7

Edit: Been thinking about it, the suggestion won't work either. Try grouping with the snippets user_id instead of the users id in your query building example.

~~How about the following?~~

~~$snippetsUsers = User::with('snippets')->get()->sortBy(function($query){return $query->snippets->count();});~~

1 like
jstoone's avatar

@dfaux that just worked perfectly. Didn't even think about just get()'ing it and sorting. What a bomb!

Thank you!

Please or to participate in this conversation.