How to Get Random Records in Laravel

Hi, Artisan. today I am going to show you how to get random records from the Database in laravel. Laravel makes it very easy for us. We use inRandomOrder() method to ger random records in laravel.

Read also: Create a new Laravel 8.0 project

This section will instruct you on how to use the inRandomOrder() method to get random database records from laravel.

Notice that it is possible to use the Laravel inRandomOrder method to randomly sort the query data. If, for instance, you want to get random DB posts in Laravel. So you can also use the following techniques below.

 Retrieve Random Records From DB with Eloquent

public function index()
{
    $posts = DB::table('posts')
                ->inRandomOrder()
                ->limit(5)
                ->get();
}

Retrieve Random Records From DB using Model

public function index()
{
    $posts = Post::inRandomOrder()
                ->limit(5)
                ->get();
}

Hope it helps you!