Laravel advanced search query fix

后端 未结 8 1305
终归单人心
终归单人心 2021-01-28 21:34

I have a search form with multiple input and select boxes I need help to get if conditions in my query in order to each part works separately and all at once.

he

8条回答
  •  别那么骄傲
    2021-01-28 22:09

    SOLVED

    After weeks of playing with codes finally I came to the right results for myself (in my case it works this way for others maybe works with other suggested answers)

    public function advancedsearch(Request $request) {
        $options = Option::all();
        $brands = Brand::all();
        $brandss = Input::has('brands') ? Input::get('brands') : [];
        $suboption = Input::has('suboptions') ? (int)Input::get('suboptions') : [];
        $min_price = Input::has('min_price') ? (int)Input::get('min_price') : null;
        $max_price = Input::has('max_price') ? (int)Input::get('max_price') : null;
    
        //codes
        if(count($request['suboptions'])){
          $products = DB::table('products')
          ->join('product_suboption', function ($join) {
            $suboption = Input::has('suboptions') ? Input::get('suboptions') : [];
                $join->on('products.id', '=', 'product_suboption.product_id')
                     ->where('product_suboption.suboption_id', '=', $suboption);
            })
          ->paginate(12);
        }
    
        elseif(count($request['brands'])){
          $products = DB::table('products')
          ->whereIn('products.brand_id', $brandss)
          ->paginate(12);
        }
    
        elseif(count($request['min_price']) && count($request['max_price'])){
          $products = DB::table('products')
          ->whereBetween('price', [$min_price, $max_price])
          ->paginate(12);
        }
    
    
        return view('front.advancesearch', compact('products', 'brands', 'options'));
        }
    

    NOTE: most of my pricing issues solved with (int) as you see in my codes (int)Input::get('min_price') and (int)Input::get('max_price').

    Special thanks to Ravindra Bhanderi for his count($request[''] suggestion.

提交回复
热议问题