Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

eloquent - 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. Any ideas?

EDIT:

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

question from:https://stackoverflow.com/questions/26983186/how-get-random-row-laravel-5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 AppQuotation; // 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...