[12.x] Add findRand() method to Eloquent Builder for random record selection
feat: add findRand() method to Eloquent Builder
Add findRand() method for convenient random record retrieval that follows the existing find* method family pattern. Supports single and multiple record selection with consistent return types.
- Add findRand($count = 1, $columns = ['*']) method
- Returns TModel|null for single records (count = 1)
- Returns Collection for multiple records (count > 1)
- Maintains consistency with existing find* methods
- Includes comprehensive test coverage
- Improves developer experience for common random selection use case
Examples:
User::findRand() // Single random user
User::findRand(5) // Collection of 5 random users
Post::published()->findRand(3, ['title', 'slug']) // 3 random published posts
Fixes common anti-pattern of User::all()->random() and provides
intuitive API for database-level random record selection.
At the risk of being smart-alecky here: Is it really "finding" (or "searching" to begin with) something if we say "give me whatever"?
That being said (or asked to be precise 😉), I would suggest, naming it getRand(om).
- Add findRand($count = 1, $columns = ['*']) method
- Returns TModel|null for single records (count = 1)
- Returns Collection for multiple records (count > 1)
- Maintains consistency with existing find* methods
Coincidentally, find() usually just returns one record (TModel), while all() and get() tend to return multiple (Collection<TModel>)
Fixes common anti-pattern of User::all()->random()
However, Laravel already has inRandomOrder() and limit(). People just need to learn the difference between executing stuff on the database or on the collection.
Why findRand and not findRandom? What is the benefit of needlessly omitting two characters from a six-letter word?
I don't know, all find and related methods expect an id or an array of ids, this changes the expectation where one could think that findRandom([1, 2, 3]) would be a thing by picking a random id and returning it instead of specifying a count. find methods also are more consistent with if array = Collection, if single id = Model|null. Why here findRandom(0) is a collection but findRandom(1) is a Model|null and then findRandom(2) is again a Collection. I'd rather just use ->inRandomOrder()->limit()->get/first() to always have a Collection or a Model depending on expectation.
Thanks for your pull request to Laravel!
Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.
If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!