Skip to content

Instantly share code, notes, and snippets.

@vlakoff
Created February 24, 2016 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlakoff/b339836b3dbcedfa2a34 to your computer and use it in GitHub Desktop.
Save vlakoff/b339836b3dbcedfa2a34 to your computer and use it in GitHub Desktop.
Add orderByRandom() to Laravel query builder
<?php
// github.com/laravel/framework/issues/5223
// github.com/laravel/framework/pull/5435
use Illuminate\Database\Query\Builder;
Builder::macro('orderByRandom', function () {
$randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $this->orderByRaw($randomFunctions[$driver]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment