Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tehseen's avatar

Product filter query return me 500 why.

Query filter not working i just use filters but when i set query without filter like below it works but in second case i add the filter but its throw 500 why please help.

This works in first case return all products

$products = Product::where(function($query){
            
})->get();

echo json_encode($products);

But when i try to enter filter by price free or paid it return 500 like below

	
$filterValues = array();
parse_str($request->formData, $filterValues);

$products = Product::where(function($query){

	$free = isset( $filterValues['free'] ) ? 'yes' : null;
	if(isset($free) ){
             $query->orwhere('price','<=','0');
        }
            
})->get();

echo json_encode($products);

0 likes
3 replies
Ashraam's avatar
$filterValues = array();
parse_str($request->formData, $filterValues);

$products = Product::where(function($query) use(filterValues) {

	$free = isset( $filterValues['free'] ) ? 'yes' : null;
	if(isset($free) ){
             $query->orwhere('price','<=','0');
        }
            
})->get();

echo json_encode($products);

Add the use word in the function if you want to use a variable outside the function

DiogoGomes's avatar

You are using $filterValues inside a closure without "using it".

Also orwhere does not exist. You should use orWhere or simply where in this case.

$products = Product::where(function($query) use ($filterValues) {
	$free = isset( $filterValues['free'] ) ? 'yes' : null;
	if(isset($free) ){
             $query->where('price','<=','0');
        }
            
})->get();

By the way, there's an helper function when that will clean that a lot:

$products = Product::when(isset( $filterValues['free'] ), function($query) {
             $query->where('price','<=','0');
})->get();

Please or to participate in this conversation.