php - Loop parameters through a query collection and then merge them (Laravel 8)

Solution:

Your current code executes one query per parameter/condition. You could do:

$query = SupportGuideTranslation::query();

foreach($request->query() as $key => $value){
   $query->where($key, $value);
}

$guides = $query->get();

I would also advise you to check that the parameter actually exists on the table before adding it to the query. If I make a request with active=1&non_existing_column=2 your code would throw an error.

Answer

Solution:

        $guides = new Collection;
        foreach($request->query() as $key => $value){
            if($guides->isEmpty()){
                $guides = SupportGuideTranslation::where($key, $value)->get();
            }
            else{
                $guides = $guides->toBase()->merge(SupportGuideTranslation::where($key, $value)->get());
            }
        }


        $guides = $guides->unique();

Answer

Solution:

where() can take an array. So you don't necessarily need to loop:

SupportGuideTranslation::where($request->query())->get();

If that doesn't work for you and you have to loop over the query params, that might help:

$guides = new Collection;
foreach($request->query() as $key => $query){
   $guides = $guides->merge(SupportGuideTranslation::where($key, $query)->get());
}
$guides = $guides->unique();

Source