how get random row laravel-5

前端 未结 9 681
花落未央
花落未央 2021-02-02 07:12

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: Lar

9条回答
  •  一个人的身影
    2021-02-02 07:32

    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:

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

提交回复
热议问题