Skip to content

[12.x] Add findRand() method to Eloquent Builder for random record selection #56005

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: 12.x
Choose a base branch
from

Conversation

Ashot1995
Copy link
Contributor

@Ashot1995 Ashot1995 commented Jun 12, 2025

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.

@Ashot1995 Ashot1995 force-pushed the feature/eloquent-find-rand-method branch 4 times, most recently from b0c1eb8 to 330fc81 Compare June 12, 2025 04:44
@Ashot1995 Ashot1995 changed the base branch from 12.x to master June 12, 2025 04:46
@Ashot1995 Ashot1995 changed the base branch from master to 12.x June 12, 2025 04:47
@Ashot1995 Ashot1995 force-pushed the feature/eloquent-find-rand-method branch from 979d662 to 6a2c3dc Compare June 12, 2025 04:50
@Ashot1995 Ashot1995 marked this pull request as draft June 12, 2025 04:53
@Ashot1995 Ashot1995 changed the title Add findRand() method to Eloquent Builder for random record selection [12.x] Add findRand() method to Eloquent Builder for random record selection Jun 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant