Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get random row laravel-5

In L-4 it was simple:

$random_quote = Quotation::all()->random(1); 

But now in L-5 not a single method described in this post is working: Laravel - Eloquent or Fluent random row

My view file just gets blank.

like image 959
Peter Avatar asked Nov 17 '14 22:11

Peter


2 Answers

These works but probably you didn't use the right namespace, just use the use statement at the top of your class name like this:

<?php namespace SomeNamespace;  use App\Quotation; // Says "Quotation.php" is in "App" folder (By default in L-5.0)  class someClass {     //... } 

Then you may use in your method something like this:

// You may add: use DB; at the top to use DB instead of \DB $random_quote = Quotation::orderBy(\DB::raw('RAND()'))->first(); 

Or this:

$random_quote = Quotation::orderByRaw("RAND()")->first(); 

Update (Since Laravel - 5.2):

$random_quote = Quotation::inRandomOrder()->first(); 
like image 87
The Alpha Avatar answered Oct 06 '22 00:10

The Alpha


random() gives error in 5.2, so instead u can use inRandomOrder https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset ,

and it works on Eloquent like

Model::inRandomOrder()->first() 
like image 41
ctf0 Avatar answered Oct 05 '22 23:10

ctf0