Skip to main content
Tutorial Free

Eloquent: how to get random rows

August 17, 2015
1 min read
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!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

Asfia Aiman avatar

Just used it today and loved it. Thanks for posting