Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
viji Avatar asked Nov 21 '25 07:11

viji


1 Answers

Thanks to @viji comment, you can do it by utilizing php use keyword:

$var = 5;
$orgs = app('db')->table('t')
        ->where('status', '=', '1')
        // Sending $var to anonymous function
        ->where(function ($query) use ($var) {
            $query->where('orgs.name', 'like', "%$var%");
        })->select('id')
        ->get();
like image 115
hpaknia Avatar answered Nov 22 '25 20:11

hpaknia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!