how get random row laravel-5

前端 未结 9 663
花落未央
花落未央 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:38

    UPDATE FOR LARAVEL 5.3

    I was happy to discover this is now a native query function! :D

    The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

    $randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
    

    Unfortunately none of these answers make full use of Laravel 5's collections. If you came here from Google, like me, looking for a completely native solution please look below!

    The Answer from The Alpha has the Database dependency flaw and Benjamin's, as he pointed out, may pose a problem when rows are removed in between. Highly unlikely, but still possible.

    Here's a a one line solution to select random rows in Laravel 5+

    // The setup
    $numberOfRows = 4;
    $models = Model::all(); // or use a ::where()->get();
    
    // And the actual randomisation line
    $randRows = $models->shuffle()->slice(0,numberOfRows);
    

    Et voila - happy coding! Vote it up when you see it so it'll rise on the page :)

提交回复
热议问题