viji viji - 1 year ago 106
MySQL Question

Undefined variable in fluent query builder

I am starting to use the Laravel framework, and I have a problem with the fluent query builder. In a where condition, if I am using raw values or

, it retrieves the results and executes correctly, but when I use an assigned variable it shows "Undefined variable" errors.

$properties = Listing::where(function($query)
if (Input::has('property-type')) $query->where('property_type', '=',Input::get('property-type'));

it works correctly, but if I do

$properties = Listing::where(function($query)
if ($pt!='') $query->where('property_type', '=',$pt);

it returns the error

Undefined variable: pt

If I print the variable "$pt" it contains the value.

I want to use only the variable values, because I should pass these value from the controller to the model as parameters, and build the query in the model function. Am I doing something wrong? Is the variable not assigned before the query execution? Please, can anyone help me to resolve this?

Answer Source

The reason you are struggling with the variable is because it's outside of the anonymous function's scope.

I wouldn't worry about passing variables to the models to construct the query, simply use the awesome Input class methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download