-
-
Save vlakoff/8c8a9c8ee9437d3c1a94 to your computer and use it in GitHub Desktop.
Laravel Eloquent Agnostic Random Statement
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 | |
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