Home > Backend Development > PHP Tutorial > How to Retrieve Random Rows in Laravel Using Eloquent or Fluent?

How to Retrieve Random Rows in Laravel Using Eloquent or Fluent?

Patricia Arquette
Release: 2024-11-16 12:31:03
Original
479 people have browsed it

How to Retrieve Random Rows in Laravel Using Eloquent or Fluent?

Selecting Random Rows with Eloquent or Fluent in Laravel

Retrieving random rows from a database table is a common task in web applications. Laravel provides several methods to accomplish this task using either the Eloquent or Fluent query builder.

Using Eloquent (Laravel >= 5.2)

Since Laravel 5.2, the framework introduced the inRandomOrder() method which provides a convenient way to retrieve random rows. The following code illustrates how to use it:

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

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

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

Alternatively, you can use the random() method provided by collections to retrieve a single random record:

$randomUser = User::all()->random();
Copy after login

Using Fluent (Laravel < 5.2)

For versions of Laravel prior to 5.2, you can use Fluent's orderByRaw() method to order the results randomly:

$randomUsers = User::orderByRaw(DB::raw('RAND()'))->get();<p><strong>Using SQL with Fluent</strong></p>
<p>If you prefer to use pure SQL, you can write the following query in your Fluent statement:</p>
<pre class="brush:php;toolbar:false">$randomUsers = DB::table('users')->orderByRaw('RAND()')->get();
Copy after login

Note that this approach requires you to count the number of records prior to the initial query, which can be inefficient for large datasets.

Conclusion

Selecting random rows in Laravel can be achieved using either Eloquent or Fluent. The inRandomOrder() method in Eloquent provides the most efficient and straightforward way to do this for Laravel 5.2 and above. For older versions, Fluent's orderByRaw() method offers a viable alternative, although it has some limitations.

The above is the detailed content of How to Retrieve Random Rows in Laravel Using Eloquent or 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