nicwek's avatar

Using Ajax to Filter Brands in Laravel Ecommerce

I am following up on an online tutorial to explain on how to implement product brand filters in a laravel e-commerce. The filter uses ajax and checkboxes where a user clicks on a checkbox to filter according to the brand. The filter works well when checking the checkboxes, the issue comes in when i want to uncheck and go back to no filter. The page called in the controller duplicates itself in the window where filtering occurs. I have tried finding a solution for several days now, I will surely appreciate all effort. Or alternatively is there an easier way to implement product filtering in ecommerce without reload with checkboxes instead of using ajax.

Here is my controller function

public function allproducts(Request $request)
    {
        if ($request->ajax() && isset($request->start)) {
            $start = $request->start; // min price value
            $end = $request->end; // max price value

            $products = DB::table('products')
                ->where('price', '>=', $start)->where('price', '<=', $end)->orderby('price', 'ASC')->paginate(6);

            $categories = Category::whereNull('parent_id')->get();
            //dd($products);
            response()->json($products); //return to ajax
            response()->json($categories); //return to ajax
            return view('product.product', ['allProducts' => $products]);

        } else if (isset($request->brand)) {

            $brand = $request->brand; //brand

            $products = DB::table('products')->whereIN('brand', explode(',', $brand))->paginate(6);
            $categories = Category::whereNull('parent_id')->get();
            //dd($products);
            response()->json($products); //return to ajax
            response()->json($categories); //return to ajax
            return view('product.product', ['allProducts' => $products]);

        } else {

            $products = DB::table('products')->paginate(12);
            $categories = Category::whereNull('parent_id')->get();
            return view('product.all', ['allProducts' => $products, 'categories' => $categories]);

        }

    }
0 likes
0 replies

Please or to participate in this conversation.