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
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.
You can try as:
$galleries = App\Gallery::orderByRaw('RAND()')->get()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With