How to Efficiently Retrieve Random Rows from MySQL in Laravel

This guide explains three Laravel techniques—native SQL with ORDER BY RAND(), raw expressions, and the inRandomOrder method—to efficiently retrieve a random set of rows from a MySQL database for tasks such as assigning orders or sampling users.

php Courses
php Courses
php Courses
How to Efficiently Retrieve Random Rows from MySQL in Laravel

Laravel often needs to fetch random rows from a MySQL database, for example to assign orders or sample users.

1. Using native SQL MySQL supports ORDER BY RAND() together with LIMIT to select a random subset. SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100; In Laravel you can run the same statement with DB::select():

$info = DB::select('SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100');

2. Using raw expressions Laravel’s query builder allows DB::raw('RAND()') or orderByRaw('RAND()') to achieve the same effect.

$info = self::where('dealing', '<>', '')
->orderBy(DB::raw('RAND()'))
->take(5)
->get();

3. Using the inRandomOrder method Laravel provides inRandomOrder() which automatically adds a random ordering clause.

$info = DB::table('users')
->inRandomOrder()
->take(5)
->get();

For the full article, click the “Read original” link below.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPLaravelRandom Data
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.