Skip to content

Commit 6a2c3dc

Browse files
committed
Add findRand() method to Eloquent Builder for random record selection
1 parent 3ea6180 commit 6a2c3dc

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,24 @@ public function find($id, $columns = ['*'])
477477
return $this->whereKey($id)->first($columns);
478478
}
479479

480+
/**
481+
* Retrieve one or more random model instances.
482+
*
483+
* @param int $count
484+
* @param array $columns
485+
* @return \Illuminate\Database\Eloquent\Model|null|\Illuminate\Database\Eloquent\Collection
486+
*/
487+
public function findRandom(int $count = 1, array $columns = ['*'])
488+
{
489+
if ($count < 1) {
490+
return $this->newModelInstance()->newCollection();
491+
}
492+
493+
return $count === 1
494+
? $this->inRandomOrder()->first($columns)
495+
: $this->inRandomOrder()->limit($count)->get($columns);
496+
}
497+
480498
/**
481499
* Find a sole model by its primary key.
482500
*

0 commit comments

Comments
 (0)