Php mysql multiple parameter filter
I have a database of tours and want to sort by 3 parameters at the same time (destination country, departure date, hotel).
So I created three html inputs (destination, date, hotel)
<form action="/search-tours" method="GET">
<input name="destination" type="text">
<input name="date" type="date">
<input name="hotel" type="text">
<button type=submit>Search tours</button>
I'm using Laravel, so my php code is in the controller ("Tour" is the model = join to the "tours" table in the DB).
$destination = $request->get('destination');
$date = $request->get('date');
$hotel = $request->get('hotel');
$tours = Tour::where('destination', '=', $destination)
->where('departure', '=' , $date)
->where('hotel', '=', $hotel)
->get();
It gives correct results when I submit all inputs, but when it is missing it doesn't work at all.
I thought I could solve this through If-else, but then I realized that there could be 7 situations (1 parameter is present, 0 is missing: for ex destination (1) -date (0) -hotel (0) = 100 and total: 111, 100, 010, 001, 110, 011, 101 - we don't care about 000). And if we have 4 inputs, it will be 15, 5 parameters - 31, etc.
So it would be tedious to write so many if-else, so there is another appoach.
What approach should be taken to make it work if only 1 or 2 inputs were provided?
source to share
$query = (new Tour)->newQuery();
if($request->has('destination')){
$query->where('destination', '=', $request->get('destination'));
}
if($request->has('date')){
$query->where('departure', '=', $request->get('date'));
}
if($request->has('hotel')){
$query->where('hotel', '=', $request->get('hotel'));
}
$tours = $query->get();
source to share