Skip to content

Instantly share code, notes, and snippets.

@wayneashleyberry
Last active May 27, 2016 07:53
Show Gist options
  • Save wayneashleyberry/77b7d7d63e40dd33c3b2599ff4031563 to your computer and use it in GitHub Desktop.
Save wayneashleyberry/77b7d7d63e40dd33c3b2599ff4031563 to your computer and use it in GitHub Desktop.
Random ordering query scope
<?php
namespace App\Scopes;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\Eloquent\Builder;
trait Random
{
/**
* Random ordering query scope.
*
* @param Illuminate\Database\Eloquent\Builder $q
* @return Illuminate\Database\Eloquent\Builder
*/
public function scopeRand(Builder $q)
{
$connection = $q->getQuery()->getConnection();
if ($connection instanceof MySqlConnection) {
return $q->orderByRaw('RAND()');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment