Here are several ways to retrieve random rows from your database using Laravel 12's Eloquent.
Method 1: Using `inRandomOrder()`
<?php
// Get a single random model
$randomUser = User::inRandomOrder()->first();
// Get multiple random models (5 in this case)
$randomPosts = Post::inRandomOrder()->take(5)->get();
// With conditions
$activeProducts = Product::where('active', true)
->inRandomOrder()
->limit(3)
->get();
?>
Method 2: Using `orderByRaw('RAND()')`
<?php
// For MySQL
$randomItems = Item::orderByRaw('RAND()')->take(3)->get();
// For PostgreSQL
$randomItems = Item::orderByRaw('RANDOM()')->take(3)->get();
// For SQLite
$randomItems = Item::orderByRaw('RANDOM()')->take(3)->get();
?>
Method 3: Getting random rows efficiently for large tables
For large tables, `inRandomOrder()` can be slow. Here's a more efficient approach:<?php
// First get the count
$count = Product::count();
// Get random IDs (3 in this case)
$randomIds = range(1, $count);
shuffle($randomIds);
$randomIds = array_slice($randomIds, 0, 3);
// Get the actual records
$randomProducts = Product::whereIn('id', $randomIds)->get();
?>
Method 4: Using raw SQL for better performance
<?php
// MySQL
$randomUsers = User::whereRaw('id >= (SELECT FLOOR(MAX(id) * RAND()) FROM users)')
->orderBy('id')
->take(5)
->get();
// PostgreSQL
$randomUsers = User::whereRaw('id >= (SELECT FLOOR(MAX(id) * RANDOM()) FROM users)')
->orderBy('id')
->take(5)
->get();
?>
Method 5: Using a scope in your model
Add this to your model:<?php
public function scopeRandom($query, $limit = 1)
{
return $query->inRandomOrder()->limit($limit);
}
?>
Then use it like this:
<?php // Get one random user $user = User::random()->first(); // Get 5 random posts $posts = Post::random(5)->get(); ?>Performance Considerations: -> For small tables, `inRandomOrder()` is fine -> For large tables, consider Method 3 or 4 for better performance -> If you need truly random results for security purposes, consider more sophisticated approaches Choose the method that best fits your database size and requirements.