mercredi 8 janvier 2020

Laravel ajax pagination with original collection

I have a catalogue of products which can be filtered by a few different select, and checkbox elements. The filter actions are posted to a SearchController via ajax so as the user filters, the results are shown instantly. The search terms/variables are not appended to the URL.

I had an issue with pagination as the default Laravel pagination reloads the page, therefore, losing what the user had already filtered. I changed the pagination to work over ajax in an attempt to swiftly resolve the issue.

My issue is the ajax pagination re-runs the SearchController in order to get the collection to offset the results. The search criteria again is then reset as the filters aren't posted with the pagination ajax.

I want to just offset the original collection when called via my pagination ajax. Does this result set exist and be reused?

public function filter(Request $request, Stock $Stock)
{
// Enable query log
DB::enableQueryLog();

$Stock = $Stock->newQuery();

if($request->has('model')) {
    $the_model = $request->model;
    $request->request->add([$the_model => 1]);
}

if ($request->has('car') && $request->input('car') == 'true') {
    $Stock->orWhere('car', 1);
}

if ($request->has('bike') && $request->input('bike') == 'true') {
    $Stock->orWhere('bike', 1);
}

if ($request->has('productTypes_chosen')) {

    $Stock->whereIn('productType', $request->productTypes_chosen);
}

if ($request->has('manufacturers_chosen')) {
    $Stock->whereIn('manufacturer', $request->manufacturers_chosen);
}

$Stock->where('show_website', 1);

$stockItems = $Stock->get();
$stockItems = $Stock->paginate(15);

if($request->ajax()) {
    $view = view('partials.filtered-results')->with(compact('stockItems'));
    $view = $view->render();
    return $view;
}
}

Pagination AJAX

$(function() {
    $('body').on('click', '.pagination a', function(e) {
        e.preventDefault();

        var url = $(this).attr('href');
        getStock(url);
        window.history.pushState("", "", url);
    });

    function getStock(url) {
        $.ajax({
            url : url
        }).done(function (data) {
            $('.machines').html(data);
            $('html, body').animate({
                scrollTop: $('.machines').offset().top - 150
            }, 'slow');
        }).fail(function () {
            alert('Stocklist could not be loaded.');
        });
    }
});


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire