Skip to content

Instantly share code, notes, and snippets.

@NasirNobin
Created June 11, 2021 10:26
Show Gist options
  • Select an option

  • Save NasirNobin/1f709b33c6e61509375539dcc929e4c6 to your computer and use it in GitHub Desktop.

Select an option

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
<?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