Reputation: 1652
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?
Upvotes: 3
Views: 1524
Reputation: 3118
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();
Upvotes: 2
Reputation: 700
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.
Upvotes: 0