9

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.

5
  • 2
    stackoverflow.com/questions/13917558/… Commented Mar 5, 2019 at 9:44
  • 3
    Simple Model::all()->random(1); will work for you Commented Mar 5, 2019 at 9:45
  • I have seen that but there is no where condition Commented Mar 5, 2019 at 9:46
  • I know that, but i need make it with where clause . like Modell::where('condition')->random(1); Commented Mar 5, 2019 at 9:47
  • Just to clarify, would you like to fetch a random row or a random number of rows? Commented Mar 5, 2019 at 9:59

2 Answers 2

15

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sooo much it work......
5

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

4 Comments

I have tried it, but i return no row.
Then it sounds like your query doesn't have any results.
I try it again now it work thank you..
yes exactly..... that was the reason

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.