Laravel - Paginate Random records

前端 未结 3 1939
北荒
北荒 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:18

    Solution with Laravel + Eloquent

    Before Eloquent query, set the session variable. I used time() for the session value, so I can keep the same ordering for a certain amount of time. For example, 3600 seconds (1 hour).

    if ($request->session()->has('session_rand')) {
    
        if((time() - $request->session()->get('session_rand')) > 3600){
            $request->session()->put('session_rand', time());
        }
    }else{
        $request->session()->put('session_rand', time());
    }
    

    Add ->orderBy() to the Eloquent query using DB::raw() and the session variable that we set above:

    ->orderBy(DB::raw('RAND('.$request->session()->get('session_rand').')'))
    

提交回复
热议问题