Search code examples
laravelsql-order-by

Laravel OrderBy Random


As a novice in Laravel, i'm trying to display the images of a gallery randomly. In routes.php, I currently have this code:

// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->get();

Do you have any idea to make it work?

Thanks


Solution

  • For Laravel >= 5.2 you could use inRandomOrder() method.

    Description : The inRandomOrder() method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

    Example :

    $galleries = App\Gallery::inRandomOrder()->get();
    //Or
    DB::table('gallery')->inRandomOrder()->get();
    

    For other versions >= 5.0 you could use random() method.

    Description : The random() method returns a random item from the collection.

    Example :

    App\Gallery::all()->random()->get();
    

    Hope this helps.