In this blog post, we’ll take a look at how to get random rows in Laravel database. We’ll explore the use of the QueryBuilder
, Eloquent
, and the DB
facade. laravel has inbuilt eloquent method to get the random records from database using the inRandomOrder
method. we will understand the random records order by in laravel with example.
This example will work in all version of laravel including laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.
Why would you want to select random rows from a database?
There are several reasons you might want to do this. Maybe you want to select a winner for a contest, or randomly display products or articles on a page. Whatever the reason, Laravel makes it easy to select random record from a database.
How to Select Random Rows with Laravel
There are three ways to select random rows with Laravel: the QueryBuilder
, Eloquent, and the DB facade.
1. Select Random Rows with Laravel QueryBuilder
With the QueryBuilder
, you can use the DB::table method with inRandomOrder
to select random rows:
DB::table('articles')->inRandomOrder()->limit(5)->get();
2. Select Random Rows with Laravel Eloquent
If you’re using Eloquent, you can use the inRandomOrder
method on a query:
Article::inRandomOrder()->limit(5)->get();
2. Select Random Rows with Laravel Eloquent
If you’re using Eloquent, you can use the inRandomOrder
method on a query:
Article::inRandomOrder()->limit(5)->get();
3. Select Random Rows with DB raw query
Finally, you can use the DB facade to select random rows using RAND() function of mysql:
DB::select('SELECT * FROM articles ORDER BY RAND() LIMIT 5');
Each of these methods will return an array of randomly selected User objects.
Conclusion:
There are several reasons you might want to select random rows from a database. Maybe you want to select a winner for a contest, or randomly display products or articles on a page. Whatever the reason, Laravel makes it easy to select random rows from a database.