Content Index
- Get a random record with Eloquent
- Several records
- Use inRandomOrder() in Laravel
- Differences between random() and inRandomOrder()
- Get several random records with limit() or take()
- Use orderByRaw('RAND()') for random records
- When to use orderByRaw() instead of inRandomOrder()
- Random records in Eloquent using relationships (whereHas)
- Filter records before applying random order
- Performance considerations when using random queries
- FAQs — Frequently Asked Questions
- Conclusion
When you work with Laravel, sooner or later a very common need arises: to get one or several random records from the database. Whether to show related posts, recommendations, featured content or simply to vary results, Eloquent offers several ways to do it... although not all of them are equally recommended.
In this article I am going to show you the best ways to get random records in Laravel using Eloquent, when to use each one and what you should take into account so as not to make performance mistakes.
Get a random record with Eloquent
The inRandomOrder() method along with first():
$post = Post::inRandomOrder()->first();Several records
If you want to get random records in Laravel, we have a function called orderByRaw() which you can attach to the query you are building:
$posts = Post::orderByRaw("RAND()")->limit(5)
->pluck("title"); //get();
dd($posts);Some examples:
Illuminate\Support\Collection {#1433 ?
#items: array:5 [?
0 => "Arrays in Programming - 18"
1 => "Dismissible Widget in Flutter"
2 => "Connect a Flutter app to the Cloud Firestore database in Firebase"
3 => "Run script automatically with Cron in Linux"
4 => "Scaling and cropping images with Canvas"
]
}
Illuminate\Support\Collection {#1433 ?
#items: array:5 [?
0 => "The symbol element for SVGs in HTML"
1 => "Developing augmented reality applications with Wikitude (part 1)"
2 => "The flex-grow, flex-shrink and flex-basis properties"
3 => "What is Blender 3D? and first steps (tutorials)"
4 => "Problems with Android Studio and its projects"
]
}Remember that the where that is inside the whereHas allows us to add validations BY DEFAULT in the relationship, that is, the category, in such a way that in this case although both post and category have a column called id, by default it will look for the field (id in this case) in the category table (the relationship) if it exists, it uses the one from the relationship, and if it does not exist, it would use the one from post and orderByRaw with relationships.
The most interesting thing is that you can attach it with whereHas to be able to filter by some relationship; for example, a post has an assigned category, so:
$posts = Post::whereHas('category', function ($query) {
$query->where('id', '<', '10');
})->orderByRaw("RAND()")->limit(5)
->pluck("title"); //get();
dd($posts);Some examples:
Illuminate\Support\Collection {#1432 ?
#items: array:5 [?
0 => "Creating a live background with CSS"
1 => "4+1 essential CSS selectors when programming"
2 => "Creating an animated carousel with CSS"
3 => "Selectors in JavaScript"
4 => "Multiple layers: Effect of opening a door with CSS"
]
}
Illuminate\Support\Collection {#1432 ?
#items: array:5 [?
0 => "Multiple borders in a container with CSS"
1 => "How to make a homemade responsive grid system in CSS?"
2 => "Plugin for Cookies in JavaScript"
3 => "How to get the screen resolution with JavaScript/jQuery?"
4 => "Geometric shapes with CSS (part 2)"
]Of course, with limit() you can limit or indicate how many records you want to obtain as a maximum; this is to give you some ideas, but you can adapt other functions to it.
Otherwise, you can apply any number of additional conditions before using the orderByRaw method.
Use inRandomOrder() in Laravel
inRandomOrder() is the recommended method in modern versions of Laravel. Internally, it is responsible for applying the appropriate random function depending on the database (MySQL, PostgreSQL, etc.), which makes your code more portable.
Basic example to get several random records:
And if you want to limit the quantity:
This method is ideal when:
- You work with current versions of Laravel
- You want a clean and readable solution
- You do not need fine control over the SQL query
Differences between random() and inRandomOrder()
Here is a fairly common mistake.
random()belongs to the collections, not the SQL query.inRandomOrder()acts directly on the database.
For example:
This loads all records into memory and then selects one at random. In small tables it can work, but as soon as the volume of data grows, it ceases to be a good idea.
Instead:
You delegate the work to the database engine and avoid consuming memory unnecessarily.
Get several random records with limit() or take()
One of the most common cases is to obtain a set of random records, for example 5 different posts each time.
Here you can use either limit() or take():
In my tests with real data, running this query several times returns completely different lists, which is perfect for dynamic sections like "recommended articles" or "you might also be interested in."
Use orderByRaw('RAND()') for random records
Before inRandomOrder() existed (Laravel 5.2+), the classic way to get random records was using raw SQL:
This approach is still totally valid, and in fact I have used it in real projects when I needed more control over the query or compatibility with old code.
When you run the query several times, the results really change, as you can easily check using dd().
When to use orderByRaw() instead of inRandomOrder()
orderByRaw('RAND()') is useful when:
- You work with old versions of Laravel
- You need an explicit SQL query
- You want to combine it with more complex logic
Of course, when using raw SQL you must be clear about which database you are using, since RAND() is specific to MySQL.
Random records in Eloquent using relationships (whereHas)
This is where many guides fall short.
In real scenarios, you don't always want random records "just because", but filtered by a relationship. For example, posts that belong to certain categories.
Eloquent allows you to do this without any problem using whereHas():
The interesting thing about this approach is that you can continue chaining conditions before applying the random order. In my case, I have used it to filter by specific categories and then show varied content in each load.
In addition, the where inside whereHas acts by default on the related table, which avoids ambiguities even when both tables have columns with the same name, such as id.
Filter records before applying random order
A good practice is to apply all filters first and leave the random order for the end. In this way:
- You reduce the data set
- You improve performance
- You keep the query clear and maintainable
This becomes even more important when working with large tables.
Performance considerations when using random queries
Here it is convenient to be clear: ordering by RAND() is not free.
In tables with many records, the database engine has to:
- Calculate a random value per row
- Sort the entire set
- Return the first results
If the volume of data is very high, this type of query can become expensive. In those cases, it is convenient to:
- Always limit the number of records
- Filter as much as possible before
- Evaluate alternative strategies if traffic is high
For most small and medium-sized projects, however, the methods we have seen work perfectly.
FAQs — Frequently Asked Questions
- How to get a single random record in Laravel?
- Use
Model::inRandomOrder()->first().
- Use
- What is the best method for random records in Eloquent?
inRandomOrder()is the most recommended in current versions of Laravel.
- Can I get random records using relationships?
- Yes, by combining
whereHas()withinRandomOrder()ororderByRaw().
- Yes, by combining
- Does
RAND()affect performance?- In large tables it can be expensive, so it is convenient to limit and filter the results.
Conclusion
Getting random records in Laravel using Eloquent is simple if you choose the right method:
- Use
inRandomOrder()if you work with modern versions of Laravel. - Resort to
orderByRaw('RAND()')if you need more control or compatibility. - Avoid
random()on collections in large tables. - Combine random queries with relationships and filters for real cases.
With these techniques you can cover from the simplest case to more advanced scenarios without complicating yourself unnecessarily.