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

Yousarssif's avatar

Order By number of rows from another table

Is there any way to order data of a table based on another table. assuming I have a table "users" and another table "pictures". what can I do to show Users That have many pictures first. something like User::orderBy('num_pictures', 'ASC').

0 likes
4 replies
LaryAI's avatar
Level 58

Yes, you can achieve this by using a subquery to count the number of pictures for each user and then ordering by that count. Here's an example using Laravel's query builder:

$users = DB::table('users')
    ->select('users.*', DB::raw('COUNT(pictures.id) as num_pictures'))
    ->leftJoin('pictures', 'users.id', '=', 'pictures.user_id')
    ->groupBy('users.id')
    ->orderBy('num_pictures', 'desc')
    ->get();

In this example, we're selecting all columns from the users table and using DB::raw to count the number of pictures for each user. We're then left joining the pictures table on the user_id column, grouping by the users.id column, and ordering by the num_pictures count in descending order.

Note that this example assumes that the pictures table has a foreign key user_id that references the id column in the users table.

2 likes
Yousarssif's avatar

@LaryAI You are getting wild A.I dude, Thanks I think that will solve my problem, but is there a way using Eloquent instead of DB?

daviddelon's avatar

Old question but a search engine drove me here, from the doc and a little help of A.I this should works :


        $users=User::with(['pictures'])
        ->withCount('pictures')
        ->orderBy('pictures_count', 'desc')

1 like

Please or to participate in this conversation.