In this tutorial you will learn about the How to Get Random Records in Laravel and its application with practical example.
In this Laravel get a random record example tutorial, I’ll show you how to get random records from DB in laravel using inRandomOrder() method. In this article you will learn to get random records from DB in laravel.
How to Get Random Records in Laravel
While developing an laravel application you come to situations where you want to get random posts/data from the database in laravel. You may also want to display this random data anywhere on your laravel blog. In laravel this can be done using inRandomOrder() method to get random records in laravel. In this article I’ll guide you through step by step how to get random records from the database in laravel using inRandomOrder() method. You can also get random records from collection in laravel.
In this article I’ll share two different method to get random records from the database in laravel.
Laravel Retrieve Random Records From DB with Eloquent
In this method we will fetch the 5 random posts from DB table using eloquent in laravel:
1 2 3 4 5 6 7 |
public function index() { $data = DB::table('posts') ->inRandomOrder() ->limit(5) ->get(); } |
Laravel Retrieve Random Records From DB using Model
In this method we will fetch the 5 random posts from DB table using laravel model in laravel:
1 2 3 4 5 6 |
public function index() { $data = Post::inRandomOrder() ->limit(5) ->get(); } |