how to show random posts using sortBy()? Shows items randomly rather than in a fixed descending order
@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
@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.
@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 .
why dont you use orderBy('id','desc') .get the items by id on a descending order.
$randomUser = DB::table('users')->orderBy('id','desc')->get();
The helper function shuffle() will do exactly what you need. Check the docs here .
Please sign in or create an account to participate in this conversation.