3

I have an Eloquent model called Question linked to a database table named questions.

Is there an Eloquent function that will let me take a single random question (or a set number of random questions) from the database? Something like the following:

$random_question = Question::takeRandom(1)->get();

or

$random_questions = Question::takeRandom(5)->get();
Garry Pettet
  • 8,096
  • 22
  • 65
  • 103
  • Possible duplicate of http://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row – Quasdunk May 04 '14 at 13:42

3 Answers3

11

Simply you can do:

$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->get();

and

$random_question = Question::orderBy(DB::raw('RAND()'))->take(5)->get();

If you want to use the syntax as you specified in your question, you can use scopes. In the model Question you can add the following method:

public function scopeTakeRandom($query, $size=1)
{
    return $query->orderBy(DB::raw('RAND()'))->take($size);
}

Now you can do $random_question = Question::takeRandom(1)->get(); and get 1 random question.

You can read more about Laravel 4 query scopes at http://laravel.com/docs/eloquent#query-scopes

SUB0DH
  • 5,130
  • 4
  • 29
  • 46
1
$data = Model::where('id',$id)->get()->random($count);

You can use random. It simple and effective.

KAS
  • 790
  • 7
  • 12
  • This way is good for a few results but if you have thousands of result this method will be slow because it gets first all the results and then it picks a random one. – Alex Kyriakidis Nov 05 '15 at 00:20
0

Just use ->orderBy(DB::raw('RAND()')) in your query

$featurep= DB::table('tbl_products') ->join('tbl_product_images' , 'tbl_products.ID', '=', 'tbl_product_images.Product_ID') ->where(array('tbl_products.is_Active' => 0,'CategoryID' => $result->CategoryID)) ->groupBy('ID') ->orderBy(DB::raw('RAND()')) ->take(4) ->get();

Chamandeep
  • 116
  • 2
  • 8