Laravel - Paginate Random records

前端 未结 3 1918
北荒
北荒 2021-01-05 14:19

How we can paginate through random records in laravel? for example:

$products = Product::all()->orderBy(DB::raw(\'RAND()\'));
$products->paginate(4);
$         


        
3条回答
  •  时光说笑
    2021-01-05 15:07

    Whe you dive into the documentation of mysql and search for the RAND() functionality you will see you can use a "seed".

    By using a seed you will always get the same results that are randomised.

    Example:

    $products = Product
    
        ::all()
    
        ->orderBy(DB::raw('RAND(1234)'))
    
        ->paginate(4);
    

    You can generate your own seed and store in in a session or something to remember it.

    Update

    The Laravel query builder now has a function that does exactly the same:

    $products = Product
    
        ::all()
    
        ->inRandomOrder('1234')
    
        ->paginate(4);
    

提交回复
热议问题