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

larpajd12's avatar

how to show random posts using sortBy()?

Shows items randomly rather than in a fixed descending order

0 likes
6 replies
MaverickChan's avatar

@larpajd12

Laravel has a helper function called random() , you can chain it after your collection.

$randomUser = DB::table('users')->get()->random();

also , you can get random multiple records.

$randomUser = DB::table('users')->get()->random(12); //this will get 12 random records
1 like
Cronix's avatar

@MaverickChan No offense, but that's a very bad way to do it. You are retrieving ALL records, and then getting a few randomly from the returned collection. Think if you have a million records...

It's way better to do it in the actual query and only get what you need.

1 like
MaverickChan's avatar

@Cronix No Offense Either , if you can retrieve all data , why not filter it first then use ->random() function ?

you can change ->get() to any of your method . That was just an example.

i am giving a useful way , and of course , a good way .

kristi's avatar

why dont you use orderBy('id','desc') .get the items by id on a descending order. $randomUser = DB::table('users')->orderBy('id','desc')->get();

arthurvillar's avatar

The helper function shuffle() will do exactly what you need. Check the docs here.

Please or to participate in this conversation.