Getting Random Rows in Laravel

Getting Random Rows in Laravel

Laravel’s Query Builder has a method get() to actually get the rows, but what if we want to get random rows in Laravel without using raw SQL.

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:

SELECT * FROM products ORDER BY RAND() LIMIT 10

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 *

*

When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

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