Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 879
Vfero Avatar asked Nov 11 '16 15:11

Vfero


2 Answers

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.

like image 72
Zakaria Acharki Avatar answered Oct 28 '22 08:10

Zakaria Acharki


You can try as:

$galleries = App\Gallery::orderByRaw('RAND()')->get()
like image 31
Amit Gupta Avatar answered Oct 28 '22 09:10

Amit Gupta