Getting Random Rows in Laravel

Getting Random Rows in Laravel

Spread the word! Share with your fellow developers.

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 100 products 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:


Using Raw Expression

And in Laravel we can just use Raw expressions :

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

Shorter Way

Or even shorter:

$products = Product::orderByRaw('RAND()')->take(10)->get();

I hope this will help you.

One comment on “Getting Random Rows in Laravel

  1. You can try with :
    $products = Product::inRandomOrder()->take(10)->get();
    I think this is since Laravel v5.3.

    BTW thank you for all tuts on this site.

Leave a Reply

Your email address will not be published. Required fields are marked *



This site uses Akismet to reduce spam. Learn how your comment data is processed.