How to Select Random Rows in Laravel Using Eloquent and Fluent?

Barbara Streisand
Release: 2024-11-12 00:42:03
Original
485 people have browsed it

How to Select Random Rows in Laravel Using Eloquent and Fluent?

Selecting Random Rows in Laravel Using Eloquent and Fluent

When working with large datasets, it is often necessary to retrieve random rows from the database without having to perform a preparatory count. Laravel provides several options for achieving this using both Eloquent and Fluent interfaces.

Eloquent

Laravel 5.2 and above offers the inRandomOrder() method:

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

This method returns a collection of all random rows from the specified model. To limit the number of rows retrieved, use the limit() method:

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

To retrieve a single random row, use the first() method:

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

For older versions of Laravel (4.2.7 - 5.1), you can use the orderByRaw() method:

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

For Laravel versions 4.0 - 4.2.6, use:

User::orderBy(DB::raw('RAND()'))->get();
Copy after login

Fluent

In versions of Laravel prior to 5.2, the order_by() method was used with the DB::raw() helper function:

User::order_by(DB::raw('RAND()'))->get();
Copy after login

Additional Considerations

It is important to note that the orderBy() method does not currently allow for any arguments other than ASC or DESC. Therefore, it is necessary to use the orderByRaw() method or inRandomOrder() method for selecting random rows.

Performance Considerations

When retrieving large numbers of rows, it is important to consider the impact on performance. Using the inRandomOrder() method may be more efficient than using the orderByRaw() method, as it does not require an additional subquery to generate random ordering.

The above is the detailed content of How to Select Random Rows in Laravel Using Eloquent and Fluent?. 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