Skip to content

Instantly share code, notes, and snippets.

@vlakoff
Created February 24, 2016 04:30

Revisions

  1. vlakoff created this gist Feb 24, 2016.
    20 changes: 20 additions & 0 deletions orderByRandom.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    <?php

    // github.com/laravel/framework/issues/5223
    // github.com/laravel/framework/pull/5435

    use Illuminate\Database\Query\Builder;

    Builder::macro('orderByRandom', function () {

    $randomFunctions = [
    'mysql' => 'RAND()',
    'pgsql' => 'RANDOM()',
    'sqlite' => 'RANDOM()',
    'sqlsrv' => 'NEWID()',
    ];

    $driver = $this->getConnection()->getDriverName();

    return $this->orderByRaw($randomFunctions[$driver]);
    });