Laravel advanced search query fix

后端 未结 8 1304
终归单人心
终归单人心 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:08

    This is the method I use to search using laravel eloquent with multiple input:

    $input = Input::all(); //group all the inputs into single array
    $product = Product::with('options','suboptions','brand');
    
    //looping through your input to filter your product result
    foreach ($input as $key => $value)
    {
        if ($value!='') {
           if ($key == "max_price")
                $product = $product->where('price','<=', $value);
           elseif ($key == "min_price")
                $product = $product->where('price','>=', $value);
           elseif ($key == "brands")
                $product = $product->whereIn('brand_id', $value); //assuming that your Input::get('brands') is in array format
           elseif ($key == "suboptions")
                $product = $product->whereIn('suboption_id', $value);
        }
    }
    $product = $product->get();
    

    The method above will return all products if no input is submitted, and will filter the result based on the input if available, on top of this it's also a good practice to sanitize your inputs with validations before proceeding with the query

提交回复
热议问题