8

I am trying to fetch random number of rows from table in laravel 5.7, but i could not find any solution. I have use

 Model::all()->random(2);

It work fine. But i need to apply where clause with it like Model::select('column')->where('column','value')->random(number of rows'); So how can i achieve this using eloquent. Please any suggestions for me.

Riaz Khan
  • 247
  • 1
  • 3
  • 12

2 Answers2

13

You can simply add to chain inRandomOrder, as suggested here:

Laravel - Eloquent or Fluent random row

And then limit your dataset.

Model::select('column')
    ->where('column','value')
    ->inRandomOrder()
    ->limit(2) // here is yours limit
    ->get();
Roman Meyer
  • 2,634
  • 2
  • 20
  • 27
4

You could use the inRandomOrder method in combination with first, like this: Model::inRandomOrder()->select('column')->where('column','value')->first();

D Malan
  • 10,272
  • 3
  • 25
  • 50