Laravel get a random record example. Here you will learn how to get random records from DB in laravel using inRandomOrder() method.
You must be visiting many blogs. So sometimes you have seen these blogs in the sidebar. It is written random posts and there are some posts below it.
If you are building a blog application in laravel framework. And want to get random posts/data from the database in laravel. And want to display this random data anywhere on your laravel blog. So at that time, you need to use inRandomOrder() method to get random records in laravel.
This article will guide you on how to use get random records from the database in laravel using inRandomOrder() method. As well as get random records from collection in laravel.
Note that, Laravel inRandomOrder method may be used to sort the query results randomly. For example, if you want to get random posts from DB in laravel. So you can use the below following methods as well.
1: 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(); }
2: Laravel Retrieve Random Records From DB using Model
The following method also will fetch the 5 random posts from DB table in laravel:
/** * The attributes that are mass assignable. * * @var array */ public function index() { $data = Post::inRandomOrder() ->limit(5) ->get(); }
Conclusion
In this laravel fetch random records from database or collection, you have learned how to get random records from database and collection using inRandomOrder() method in laravel framework.
Hi, Devendra Dode, how are you? I m new in Laravel deployment apps.
Is possible to talk with you way whatsapp or email for a help and others subjects? My email is [email protected]
1. Is possible to get random records in laravel BUT of USERs? like is the code for this?
2. Is possible to mix features of 2 or more laravel apps of differents proyect? like is possible this? like will be with API REST? or MIX DATABASE?