Reputation: 503
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
Reputation: 103
if you are using laravel 8 (my case) use
$galleries = App\Gallery::inRandomOrder()->get();
Upvotes: 1
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
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
Reputation: 17678
You can try as:
$galleries = App\Gallery::orderByRaw('RAND()')->get()
Upvotes: 16