Search code examples
mysqlfluentlaravel

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 Input::get(), 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'));
})->get();

it works correctly, but if I do

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

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?


Solution

  • 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.