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
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.
I suggest a different approach.
On your controller, change it to this:
public function advancedsearch(Request $request) {
$suboptions2 = request->suboptions ? request->suboptions : null;
$min_price = request->min_price ? request->min_price : null;
$max_price = request->max_price ? request->max_price : null;
$brands2 = request->brands ? request->brands : null;
$query = Product::select('field_1', 'field_2', 'field_3')
->join('brands as b', 'b.id', '=', 'products.brand_id')
...(others joins);
// here we do the search query
if($suboptions2){
$query->where('suboptions_field', '=', $suboptions);
}
if($min_price && $max_price){
$query->where(function($q2) {
$q2->where('price', '>=', $min_price)
->where('price', '<=', $max_price)
});
}
if($brands2){
$query->where('products.brand_id', '=', $brands2);
}
// others queries
// finish it with this
$query->get();
return view('front.advancesearch', compact('products', 'brands', 'options'));
I find doing it this way is very useful because it can be really easy to implement additional queries.