Eloquent: how to get random rows

Laravel's Query Builder has a method get() to actually get the rows, but what if we want to get random rows? Like, for example, we have 30 questions 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 questions ORDER BY RAND() LIMIT 10
And in Laravel we can just use Raw expressions:
$questions = Question::orderBy(DB::raw('RAND()'))->take(10)->get();
Or even shorter:
$questions = Question::orderByRaw('RAND()')->take(10)->get();
Just a quick tip this time!

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials