21

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

4 Answers 4

62

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.

5
  • 1
    Thanks for your answer. This solution gives an error : BadMethodCallException in Builder.php line 2161: Call to undefined method Illuminate\Database\Query\Builder::inRandomOrder()
    – Vfero
    Nov 11, 2016 at 15:56
  • It seems inRandomOrder is the problem. I still have the same error.
    – Vfero
    Nov 11, 2016 at 16:07
  • 2
    it is for >= laravel 5.2.. check your laravel version Nov 11, 2016 at 16:07
  • Course::inRandomOrder()->take(20)->get(); Didn't work. - bad sort specification in Find.php line 219 Also Course::all()->random()->get(); fetches the records but with same sequence, no difference. Am i missing something. - Laravel version 5.6 Jan 29, 2019 at 7:13
  • Call to undefined method Illuminate\\Database\\Eloquent\\Builder::random() Jun 14, 2021 at 23:41
16

You can try as:

$galleries = App\Gallery::orderByRaw('RAND()')->get()
4
  • 1
    Thnaks for your answer, this solution makes no change, i still get a result as orderby ID
    – Vfero
    Nov 11, 2016 at 15:55
  • Are you running the exact query provided above or you are adding more to it?
    – Amit Gupta
    Nov 11, 2016 at 15:59
  • I just add ; at the end
    – Vfero
    Nov 11, 2016 at 16:01
  • Don't add anything else to the query, just try the exact query provided above. I have tested it myself it's working.
    – Amit Gupta
    Nov 11, 2016 at 16:32
2

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();
});
1

if you are using laravel 8 (my case) use

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.