how get random row laravel-5

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

    <?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();
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2021-02-02 07:38

    Laravel 5.4

    1) if need one random model:

    $object = Model::all()->random();
    

    2) if need many random models:

    $object = Model::all()->random($n); //$n - number of elements
                                        //$object - collection
    

    Comment: Calling $collection->random(1) will now return a new collection instance with one item.This method will only return a single object if no arguments are supplied.

    Doc ref: https://laravel.com/docs/5.4/collections#method-random

    0 讨论(0)
提交回复
热议问题