Home > Backend Development > PHP Tutorial > How to Select Random Rows in Laravel: Eloquent, Fluent, and Collections Methods?

How to Select Random Rows in Laravel: Eloquent, Fluent, and Collections Methods?

Susan Sarandon
Release: 2024-11-12 15:56:02
Original
158 people have browsed it

How to Select Random Rows in Laravel: Eloquent, Fluent, and Collections Methods?

Selecting Random Rows in Laravel: Eloquent and Fluent Approaches

In Laravel, there are multiple methods to retrieve a random row from a database table. Using Eloquent or Fluent, developers can access this functionality for various scenarios.

Eloquent Interface

Starting with Laravel 5.2, the Eloquent interface provides a dedicated inRandomOrder() method. This method shuffles the query results, effectively selecting a random row:

User::inRandomOrder()->get();
Copy after login

To specify a specific number of random records, use the limit() method:

User::inRandomOrder()->limit(5)->get();
Copy after login

Fluent Interface

For older versions of Laravel (before 5.2), you can use the Fluent interface to achieve a similar effect:

User::orderByRaw("RAND()")->get();
Copy after login

Collections Method

Alternatively, for Laravel 5.1 and above, you can use the random() method on collections generated by Eloquent queries. This approach returns a single random record or a specified number of them:

User::all()->random();
User::all()->random(10);
Copy after login

Remember to consult the official Laravel documentation for specific version compatibility and syntax variations.

The above is the detailed content of How to Select Random Rows in Laravel: Eloquent, Fluent, and Collections Methods?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template