Laravel-Infinite scroll but load data randomly on load without duplicate

Viewed 404

I have problem on loading data with infinite scroll. I want to load data randomly when user load the page or refresh the page but my problem is when i use inRandomOrder(1234) data load without any order , but its static on main page.

for example the order is like 1,5,3,2,6,4 and its never changed

but i need to this order change on every load and refresh , if user refreshed the page , now see on this order (5,6,1,3,4,2) and next time (1,5,2,4,6,3)

Controller:

$data = Table::where('enabled', 1)->inRandomOrder(2)->paginate(6);
return view('home', ['data' => $data]);

Blade:

<div class="row scrolling-pagination">
      @foreach ($data as $v)
        @include('pages.main.card')
      @endforeach
  {{ $data->links() }}
</div>

JS:

$('ul.pagination').hide();
  $(function() {
      $('.scrolling-pagination').jscroll({
        loadingHtml: 'Loading...',
        autoTrigger: true,
        padding: 0,
        nextSelector: '.pagination li.active + li a',
        contentSelector: 'div.scrolling-pagination',
        callback: function() {
            $('ul.pagination').remove();
          }
    });
  });

Im using Jscroll right now

1 Answers

Argument you pass to inRandomOrder() is seed, so if passing static arg you will always get same results for same collection. You could use rand() to generate seed, and then save it inside session data. Although if you want to change order after user refreshes you would have to make some mechanism to regenerate this seed you save, every time user refreshes site.

public function your_view_get_method(Request $request) {
    $request->session()->forget('randSeed');
    return view('home');
}

public function your_ajax_get_method(Request $request) {
    $seed = $request->session()->get('randSeed', rand());
    $data = Table::inRadnomOrder($seed)->paginate(6);
    $request->session()->put('randSeed', $seed);
    return $data;
}

This is how I would do it.

And if you want random set of data on every AJAX request, then just remove remove the argument at all.

Related