Home  >  Article  >  Backend Development  >  How do I get random rows from a database table in Laravel?

How do I get random rows from a database table in Laravel?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 16:14:10386browse

How do I get random rows from a database table in Laravel?

Getting Random Rows in Laravel

To retrieve a random row from a database table using Laravel's Eloquent ORM or Fluent query builder, there are several approaches available, depending on the Laravel version you are using.

Laravel 5.2 and Later

In Laravel 5.2 and later versions, you can utilize the inRandomOrder() method:

$randomUser = User::inRandomOrder()->first();
$randomUsers = User::inRandomOrder()->take(5)->get();

Laravel 5.1 and Prior

Prior to Laravel 5.2, you would use raw SQL syntax to achieve randomness:

$randomUser = User::orderByRaw("RAND()")->first();
$randomUsers = User::orderByRaw("RAND()")->take(5)->get();

Laravel 3

In Laravel 3, use the order_by() method with the DB::raw() function:

$randomUser = User::order_by(DB::raw("RAND()"))->first();
$randomUsers = User::order_by(DB::raw("RAND()"))->take(5)->get();

Using Collections

Alternatively, you can use the random() or random($count) methods of Collections to get a random element or array of random elements:

$randomUser = User::all()->random();
$randomUsers = User::all()->random(10);

Considerations

In SQL, the ORDER BY RAND() can be inefficient for large tables, as it requires the database engine to sort all the records. For better performance, consider using alternative approaches such as sampling or indexing.

The above is the detailed content of How do I get random rows from a database table in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn