Ad

Need To Find Another Approach To Query Search Results In Laravel/PHP

- 1 answer

I am having a really tough time figuring out another approach to do search querys on my site. At the moment i have search critierias for "Min size, Max size, City, street, Min. price, Max. price.

So i have these queries (build using Laravel standard):

if (!empty($by) && empty($adresse) && empty($minstor) && empty($maxstor)) 
        {
            $users = User::where('pris', '<', $maxpris)->where('pris', '>', $minpris)->where('by', '=', $by)->orderBy('created_at', 'DESC')->get();
        }
        elseif (!empty($by) && !empty($adresse) && empty($minstor) && empty($maxstor)) 
        {
            $users = User::where('pris', '<', $maxpris)->where('pris', '>', $minpris)->where('by', '=', $by)->where('adresse', '=', $adresse)->orderBy('created_at', 'DESC')->get();
        }
        elseif (empty($by) && !empty($adresse) empty($minstor) && empty($maxstor)) 
        {
            $users = User::where('pris', '<', $maxpris)->where('pris', '>', $minpris)->where('adresse', '=', $adresse)->orderBy('created_at', 'DESC')->get();
        }
        else
        {
            $users = User::where('pris', '<', $maxpris)->where('pris', '>', $minpris)->orderBy('created_at', 'DESC')->get();
        }

All of this simply for the user being able to search for the for the critirias above, but if i want to add several more feautures, i can just imagine how many different if functions i will need to run in order to get all the specific inputs etc. It will evovle eksponentially really quick.

How can i get around this problem without having to create hundreds of different if else statements in order to return the correct query?

Ad

Answer

You could set up an array of your filters with their corresponding operator. Then iterate over the filters that were passed and running the them (This hasn't been tested but should get you headed in the right direction):

$available_queries = [
    ['input' => 'maxpris', 'operator' => '<', 'field' => 'pris'],
    ['input' => 'minpris', 'operator' => '>', 'field' => 'pris'],
    ['input' => 'by',      'operator' => '=', 'field' => 'by'],
    ['input' => 'adresse', 'operator' => '=', 'field' => 'addresse'],
]

$query = User::orderBy('created_at', 'DESC');

foreach($available_queries as $filter){
    if(request()->input($filter['input'])){
        $query = $query->where(
            $filter['field'],
            $filter['operator'],
            request()->input($filter['input'])
        );
    }
}

$users = $query->get();

EDIT: I found an error in my original script. Updated to fix the error and make more readable.

Ad
source: stackoverflow.com
Ad