Garg Garg - 2 months ago 22
MySQL Question

Random value from database column but only one time in Laravel

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...

Answer

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
    ]);
}

Update

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