Created
June 11, 2021 10:26
-
-
Save NasirNobin/1f709b33c6e61509375539dcc929e4c6 to your computer and use it in GitHub Desktop.
Optimized way of getting (1) random item from Laravel model when it has large numbers of records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // default inRandomOrder()->first() takes a shit load of time, when we have large numbers of records in database; | |
| // here's a hack to make it a bit faster | |
| // it makes an additional `count()` query, be aware of that | |
| // add this to `AppServiceProvider@boot` | |
| Builder::macro("firstInRandomOrder", function () { | |
| return $this->skip(rand(0, ($this->count() - 1)))->first(); | |
| }); | |
| // insted of using this | |
| Model::query()->inRandomOrder()->first(); | |
| // you can call this. it's should process a bit faster than the previous one | |
| Model::query()->firstInRandomOrder(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment