Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created February 4, 2016 19:41
Show Gist options
  • Save ghostwriter/a2b7af45a0aad0bd7e36 to your computer and use it in GitHub Desktop.
Save ghostwriter/a2b7af45a0aad0bd7e36 to your computer and use it in GitHub Desktop.
Laravel Eloquent Query Scopes - OrderByRandom
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Scope a query to return a random users Model.
* https://laravel.com/docs/5.1/eloquent#query-scopes
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeRand($query)
{
static $randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $query->orderByRaw($randomFunctions[$driver]);
}
// $random_user = App\User::rand()->first();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment