作为 Laravel 的新手,我试图随机显示画廊的图像。在 路线.php ,我目前有这个代码:
// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->get();
你有什么想法让它工作吗?
谢谢
最佳答案
对于 Laravel >= 5.2 你可以使用 inRandomOrder()
方法。
Description : The
inRandomOrder()
method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
示例:
$galleries = App\Gallery::inRandomOrder()->get();
//Or
DB::table('gallery')->inRandomOrder()->get();
对于 >= 5.0 的其他版本,您可以使用
random()
方法。Description : The
random()
method returns a random item from the collection.
示例:
App\Gallery::all()->random()->get();
希望这可以帮助。
关于Laravel 随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551388/