How to Get Random Records in Laravel

Laravel get random record from database; Through this tutorial, i am going to show you how to fetch random record from database using eloquent inRandomOrder() method in laravel apps.

Sometimes, you need to fetch random data or records from database, at that time, to get random data from database in laravel app you need to use inRandomOrder() function in laravel eloquent.

Laravel Retrieve Random Records From DB with Eloquent

The following example will fetch the 5 random posts from DB table in laravel:

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    $data = DB::table('posts')
                ->inRandomOrder()
                ->limit(5)
                ->get();
}

Leave a Comment