Sergej Fomin
Sergej Fomin

Reputation: 2002

Filter with several options php mysql

I have a database of vacation tours and want to sort it by 3 parameters at the same time (country of destination, departure-date, hotel).

So I created three inputs in html form (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 am using Laravel, so my php code is in controller ("Tour" is the model = connection to a table "tours" 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 the inputs, but when any is missing it doesn't work at all.

I thought I could solve it via If-else, but then I realised that there can be 7 situations (1- parameter present, 0 - 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 would be 15, 5 params - 31 etc.

So it would be tedious to write so many if-else's, then it means there is another appoach.

What approach should I take to make it work if only 1 or 2 inputs was given?

Upvotes: 3

Views: 182

Answers (1)

Alexey Chuhrov
Alexey Chuhrov

Reputation: 1787

$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();

Upvotes: 2

Related Questions