How to retrieve random rows in Laravel eloquent

September 21, 2019

by Yunus Shaikh

Here is the code which will retrieve random rows in Laravel 6.0 eloquent


$blogs= Blog::orderByRaw('RAND()')->take(10)->get();


Here is another way to get a random row using Laravel 6.0 eloquent using inRandomOrder method.
    
        App\Post::inRandomOrder()->get()
    

Alternatively You can get a record in random order in Laravel 6.0 eloquent. Its not a recommended way if we have huge records in database. As it first takes all data from database and then apply filter on it.

    
        App\Post::all()->random(4);
    

To get a one ramdom record from database using Laravel eloquent

    
        App\Post::inRandomOrder()->first();