Vfero
Vfero

Reputation: 503

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

Upvotes: 24

Views: 60432

Answers (4)

Reda EL FILLALI
Reda EL FILLALI

Reputation: 103

if you are using laravel 8 (my case) use

$galleries = App\Gallery::inRandomOrder()->get();

Upvotes: 1

Matrix
Matrix

Reputation: 466

If you want to randomly sort a collection that has already been retrieved, you could use something like this

$result = $result->sortBy(function($item){
   return rand();
});

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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.

Upvotes: 66

Amit Gupta
Amit Gupta

Reputation: 17678

You can try as:

$galleries = App\Gallery::orderByRaw('RAND()')->get()

Upvotes: 16

Related Questions