AbehoM's avatar

Order and random results Laravel

I need to list all users on my database. Imagine that I have 10 users, a few with different ages and others with similar ages. I need to order the users by their age BUT I don't want the order of users to be the same. It sounds weird but let me show a simulation for you:

Christina Alvarado, 18
Charles Carlson, 18
Albert Hawkins, 22
Wayne Crawford, 25
Theresa Wong, 30
Jeffrey Bell, 32
Susan Cooper, 35
Amy Reyes, 22
Brian Schmidt, 22
Marie Patel, 22

If I list the users from the oldest like User::orderBy('age', 'desc')->get() I would get something like:

Susan Cooper, 35
Jeffrey Bell, 32
Theresa Wong, 30
Wayne Crawford, 25
Albert Hawkins, 22
Amy Reyes, 22
Brian Schmidt, 22
Marie Patel, 22
Christina Alvarado, 18
Charles Carlson, 18

As you can see they are now ordered by the oldest BUT I don't want them to be the same always. If you look at the 22 age they have an order and they will never change, I don't want that, I want it to be random, not always Albert Hawkins to be first, it could be Brian Schmidt, Marie Patel and so on each time the query is ran.

Is there a way to do that? Having in mind that I can't do that using the collection cause I will probably use pagination as well (cause I have more than just 10 users mentioned in the example)

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can break ties if you also order by a randomly generated value:

User::orderBy('age', 'desc')->orderByRaw('rand()')->get()

This is what the inRandomOrder() Builder method does, so:

User::orderBy('age', 'desc')->inRandomOrder()->get()
AbehoM's avatar

It worked like a charm using inRandomOrder, thank you very much.

Please or to participate in this conversation.