im trying to search using three inputs, in the first scenario when i search using all the inputs it return the result, in the second scenrio when i search by using only one field it return all the records what im trying to do is when i search with one field it return a specsific result,
public function multiSearch(Request $request){
$search = $request->input('search');
$search_1 = $request->input('search_1');
$search_2 = $request->input('search_2');
$cars = Car::query()
->where('price', 'LIKE', "%{$search}%")
->orWhere('model', 'LIKE', "%{$search_1}%")
->orWhere('transmission', 'LIKE', "%{$search_2}%")
->get();
return view('car.car-multisearch', ['cars'=>$cars]);
}
this is my blade code
<form type="get" action="{{url('/search-car')}}">
@csrf
<div class="row">
<div class="col-md-4">
<p>
<input type="text" name="search" placeholder="Price" />
</p>
</div>
<div class="col-md-4">
<p>
<input type="text" name="search_1" placeholder="Model Year" />
</p>
</div>
<div class="col-md-4">
<p>
<select name="search_2">
<option data-display="Transmission">Transmission</option>
<option value="Automatic">Automatic</option>
<option value="Manual">Manual</option>
</select>
</p>
</div>
<button type="submit" class="gauto-theme-btn">Find Car</button>
</div>
</form>
CodePudding user response:
You can dynamically add where statements to your query depending on values presence in the request and if is they are not empty. Example:
public function multiSearch(Request $request){
$cars = Car::query();
if ( $request->filled('search') ) {
$cars->where('price', 'LIKE', "%{$request->input('search')}%");
}
if ( $request->filled('search_1') ) {
$cars->orWhere('model', 'LIKE', "%{$request->input('search_1')}%");
}
if ( $request->filled('search_2') ) {
$cars->orWhere('transmission', 'LIKE', "%{$request->input('search_2')}%");
}
return view('car.car-multisearch', ['cars'=> $cars->get() ]);
}
This solution do the job but looks not good because you will need to add more if statements for each filter.)