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();
To retrieve a specific number of random records, use the limit() method:
$randomUsers = User::inRandomOrder()->limit(5)->get();
Alternatively, you can use the random() method provided by collections to retrieve a single random record:
$randomUser = User::all()->random();
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();
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!