0

i want to select several random rows from database, something like this

select * from table order by rand limit 10

how to do it in Laravel eloquent model?

nooby
  • 294
  • 4
  • 17
  • 1
    Possible duplicate of [Laravel - Eloquent or Fluent random row](http://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row) – Laerte Feb 10 '16 at 16:35

2 Answers2

2

Do something like this:

User::orderBy(DB::raw('RAND()'))->take(10)->get();
Jilson Thomas
  • 7,165
  • 27
  • 31
1

It's simple than it looks like, you just have to use the suffle() collections method.

The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)

For further methods and info you should check the laravel eloquent docs, there are methods almost for everything.

Cheers.