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

sh1r3f's avatar

orderBy a whereHas column without ignoring the unrelated data?

I have got users table related to a roles table "many to many relationship"; users are related to the roles and I want to order them by the role name so I built this query

                    User::whereHas('roles', function($query) {
                        return $query->orderBy('name');
                    });

it does what I want.. but if some users are not related to any roles they are not fetched.. I want to fetch them too but list them at the end of the records maybe.. How can I do that?

0 likes
5 replies
sh1r3f's avatar

@Sinnbeck this will lead me to refactor lots of changes. I'm trying to build a trait to be reused for many models so isn't there any other way to do it without joins?

Please or to participate in this conversation.