nooby
nooby

Reputation: 294

how to select several rows from database(eloquent) order by rand in laravel

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?

Upvotes: 0

Views: 411

Answers (2)

Victor Hugo Avelar
Victor Hugo Avelar

Reputation: 298

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.

Upvotes: 1

Jilson Thomas
Jilson Thomas

Reputation: 7303

Do something like this:

User::orderBy(DB::raw('RAND()'))->take(10)->get();

Upvotes: 2

Related Questions