Getting Random Rows in Laravel
Laravel’s Query Builder has a method
get() to actually get the rows, but what if we want to get random rows in Laravel without using raw SQL.
Like, for example, we have 100 products in the database, and want to show 10 random ones?
The bad news is there is no method
->random() instead of
get() or something like that. The good news is there is a simple solution, which is actually not so much Laravel, but more directly MySQL-related. The thing is – you can order by random in most of the databases. Here’s MySQL example:
SELECT * FROM products ORDER BY RAND() LIMIT 10
Using Raw Expression
And in Laravel we can just use Raw expressions :
$products = Product::orderBy(DB::raw('RAND()'))->take(10)->get();
Or even shorter:
$products = Product::orderByRaw('RAND()')->take(10)->get();
I hope this will help you.