How we can paginate through random records in laravel? for example:
$products = Product::all()->orderBy(DB::raw(\'RAND()\'));
$products->paginate(4);
$
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').')'))