how get random row laravel-5

前端 未结 9 661
花落未央
花落未央 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条回答
  •  闹比i
    闹比i (楼主)
    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

提交回复
热议问题