My database query return random row from database. Is there any way when page load and return this random string when user refresh the page to not change the string?
So this is my controller
public function view() {
$view = View::orderByRaw("RAND()")->limit('1')->get();
return View::make('site.view', [
'view' => $view
]);
}
And in my blade I have
@foreach($view as $rand)
{{ Form::open() }}
{{ $rand['my_view'] }}
// bunch of form fealds
<button type="submit" class="btn btn-primary">Submit</button>
{{ Form::clode() }}
@endforeach
So here user got random string and need to fill the form and add also this string. Then I save all information in database. Everything is saved perfectly in database. The problem is that user can refresh multiple time table after he submit form and can get confused when he see another random string...
Option #1 - save the data you got from the
: View::make
to a session and return it
public function view() {
$rand_view = Session::get('rand_view');
if (!$rand_view) {
$view = View::orderByRaw("RAND()")->limit('1')->get();
$rand_view = View::make('site.view', [
'view' => $view
]);
Session::put('rand_view', $rand_view);
}
return $rand_view;
}
Option #2 - for a specific user - always generate the same "random":
public function view() {
// To make sure we generate the same RAND() we generate a random seed for each user and we save that seed in the session for that user.
$rand_seed = Session::get('rand_seed');
if (!$rand_seed) {
$rand_seed = mt_rand();
Session::put('rand_seed', $rand_seed);
};
$view = View::orderByRaw("RAND({$rand_seed})")->limit('1')->get();
return View::make('site.view', [
'view' => $view
]);
}
After some debugging it seems like option #1 will not work because View::make
returns an object that can't be serialized. If you need this solution use option #2
Just save the random data into a session variable a display the contents of the session variable if it is present. Just do not forget to unset the variable when it is no longer needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.