Kritim Yantra
Apr 08, 2025
Retrieving random records from a database is a common requirement for features like:
Laravel 12 provides several efficient ways to fetch random records. This guide covers all methods with performance considerations.
inRandomOrder()
The simplest way to get random records:
// Get single random record
$randomUser = User::inRandomOrder()->first();
// Get multiple random records
$randomProducts = Product::inRandomOrder()->limit(5)->get();
ORDER BY RAND()
in MySQL// For MySQL (using RAND() with limit)
$randomPost = Post::whereRaw('RAND() < 0.01')->first();
// For PostgreSQL
$randomItem = Item::orderByRaw('RANDOM()')->first();
// Get max ID
$maxId = User::max('id');
// Get random ID
$randomId = rand(1, $maxId);
// Find record (may need to retry if ID doesn't exist)
$randomUser = User::find($randomId);
// Cache random records for 1 hour
$featuredProducts = Cache::remember('random_products', 3600, function() {
return Product::inRandomOrder()->limit(10)->get();
});
// Products with higher 'popularity' have better chance
$product = Product::orderByRaw('RAND() * popularity DESC')->first();
// Get random post with its author
$randomPost = Post::with('author')
->inRandomOrder()
->first();
$seenIds = [5, 12, 18]; // Previously shown IDs
$newRandom = Product::whereNotIn('id', $seenIds)
->inRandomOrder()
->first();
Method | Small Tables | Large Tables | Notes |
---|---|---|---|
inRandomOrder() |
✅ Excellent | ❌ Poor | Simple but slow on big data |
whereRaw('RAND()') |
✅ Good | ✅ Better | More efficient than ORDER BY RAND() |
Primary Key Method | ✅ Fast | ✅ Fastest | Requires sequential IDs |
Cached Results | ✅ Instant | ✅ Instant | Stale data trade-off |
// Controller
public function featuredProduct()
{
$product = Product::where('is_featured', true)
->inRandomOrder()
->first();
return view('home', compact('product'));
}
// Gets same random record all day
$dailyTip = Cache::remember('daily_tip', now()->endOfDay(), function() {
return Tip::inRandomOrder()->first();
});
// Store shown IDs in session
$shownIds = session('shown_article_ids', []);
$newArticle = Article::whereNotIn('id', $shownIds)
->inRandomOrder()
->first();
// Add to shown IDs
session()->push('shown_article_ids', $newArticle->id);
// Always provide fallback
$randomItem = Item::inRandomOrder()->first() ?? new Item;
where
clausesYou've learned:
✅ Multiple ways to fetch random records
✅ Performance considerations for each method
✅ Real-world implementation examples
✅ Advanced techniques for special cases
inRandomOrder()
for small datasetswhere
clauses for targeted randomness🚀 Now go implement that "Lucky Dip" feature with confidence!
📌 Need a solution for your specific case? Ask in the comments!
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google