Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created February 4, 2016 19:14
Show Gist options
  • Save ghostwriter/f86dc7812924a61bab62 to your computer and use it in GitHub Desktop.
Save ghostwriter/f86dc7812924a61bab62 to your computer and use it in GitHub Desktop.
Laravel Eloquent OrderByRandom
<?php
trait OrderByRandomTrait
{
/**
* Scope to order by random.
*
* @param \Illuminate\Database\Query\Builder $query
* @return \Illuminate\Database\Query\Builder
*/
public function scopeOrderByRandom($query)
{
static $randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $query->orderByRaw($randomFunctions[$driver]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment