Created
February 4, 2016 19:41
-
-
Save ghostwriter/a2b7af45a0aad0bd7e36 to your computer and use it in GitHub Desktop.
Laravel Eloquent Query Scopes - OrderByRandom
This file contains 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 | |
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