Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch random record using eloquent model [duplicate]

Tags:

php

laravel

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.

like image 382
Riaz Khan Avatar asked Mar 05 '19 09:03

Riaz Khan


2 Answers

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();
like image 123
Roman Meyer Avatar answered Oct 04 '22 00:10

Roman Meyer


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

like image 28
D Malan Avatar answered Oct 04 '22 01:10

D Malan