Eloquent: how to get random rows

Laravel’s Query Builder has a method get() to actually get the rows, but what if we want to get random rows? Like, for example, we have 30 questions in the database, and want to show 10 random ones?

The bad news is there is no method ->random() instead of get() or something like that. The good news is there is a simple solution, which is actually not so much Laravel, but more directly MySQL-related. The thing is – you can order by random in most of the databases. Here’s MySQL example:

SELECT * FROM questions ORDER BY RAND() LIMIT 10

And in Laravel we can just use Raw expressions:

$questions = Question::orderBy(DB::raw('RAND()'))->take(10)->get();

Or even shorter:

$questions = Question::orderByRaw('RAND()')->take(10)->get();

Just a quick tip this time!

Like our articles?
Check out our Laravel online courses!

11 COMMENTS

  1. I like orderByRaw(‘RAND()’) way how to do this.

    Christopher Lamm —

    In this way I recommend straight fetch count instead of all record.

    $rand = rand(0, Record::count() – 1);
    $randomRecord = $records->get($rand);

    return $randomRecord;

  2. It’s better to first take randomly a certain set of values and then get the resulted set “Model::orderByRaw(‘RAND()’)->take($size)->get()” than to get all column records and then sort a set within this “Model::all()->random($size)”.

    Thumbs up! @Povilas Korop

  3. performance of RAND() : very slow on huge database 10k records above

    Other concept to pick random rows :
    1. Get max id of the table
    2. Use php to generate random id , out it in a list. Example : (1,4,5,3,5,3,2) .In PHP we use rand(1,$max_id)
    3. Loop through the list and query the data
    4. Verify if that id is exist, if not, repick another id. maybe the next record of it)

LEAVE A REPLY

Please enter your comment!
Please enter your name here