Skip to content

Instantly share code, notes, and snippets.

@vluzrmos
Last active May 12, 2016 21:06
Show Gist options
  • Save vluzrmos/8046e20769a595a4b0d0 to your computer and use it in GitHub Desktop.
Save vluzrmos/8046e20769a595a4b0d0 to your computer and use it in GitHub Desktop.
Laravel Eloquent Agnostic Random Statement
<?php
trait HasRandomStatementTrait
{
/**
* Random Statements by driver name.
* @var array
*/
protected $randomStatements = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
/**
* Default random statement.
*
* @var string
*/
protected $defaultRandomStatement = 'RANDOM()';
/**
* Scope to order by random statement.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $driver
* @return \Illuminate\Database\Query\Builder
*/
public function scopeOrderByRandom($query, $driver = null)
{
return $query->orderByRaw($this->getRandomStatement($driver));
}
/**
* Get random statement for a given driver name.
*
* @param string $driver
* @return string
*/
public function getRandomStatement($driver = null)
{
$driver = $driver ?: $this->getCurrentDriverName();
if (isset($this->randomStatements[$driver])) {
return $this->randomStatements[$driver];
}
return $this->defaultRandomStatement;
}
/**
* Get the driver name for the current connection.
*
* @return string
*/
public function getCurrentDriverName()
{
return $this->getConnection()->getDriverName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment