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

charlieBrown's avatar

whereHas with orderBy in the first query

I have read some answers over here but I'm not able to adapt it to my problem. I would like to order a collection where I use whereHas. I have two tables profissao_user and users. It is returning the users but I would like to orderBy the table profissao_user by desc order on raio_deslocacao.

$users = User::whereHas('profissoes', function ($query){
        $query->where('profissao_id', 1)
        ->orderBy('profissao_user.raio_deslocacao', 'desc');
    })->where('concelho_id', 2)->get();

I would like to order it by raio_deslocacao. As you can guess the result returned is not sorted by desc order. I have tested switing desc to asc but it doens't change the order. If I do something alone these lines

$users = User::whereHas('profissoes', function ($query){
        $query->where('profissao_id', 1);
    })->where('concelho_id', 2)->orderBy('stars', 'desc')->get();

It works wonders (ordering the outer statment). What am I missing here?

0 likes
2 replies
charlieBrown's avatar
charlieBrown
OP
Best Answer
Level 2

Actually I needed to use a join to put everything into a nice little querie. Here is the full code if it's usefull to you:

$users =    User::join('profissao_user', 'users.id', '=', 'profissao_user.user_id')
                ->where('concelho_id', 2)
                ->where('profissao_id', 1)
                ->orderBy('raio_deslocacao', 'asc')
                ->get();
3 likes
Snapey's avatar

you can put orderBy on your relation if you want to use nested models (or create a new relation as well as your existing one)

Please or to participate in this conversation.