Reputation: 7013
In a model I got a scope function with 3 parameters, $query
, $sort_by
and $sort_dir
, I can access them before the join function, but for some reason I can't access inside the join function.
Why? Am I missing something?
public function scopeOrder($query, $sort_by=false, $sort_dir='ASC'){
if(!$sort_by)
return $query;
var_dump($sort_dir); //prints 'ASC'
return $query->join('product_translations', function($q){
var_dump($sort_dir); //variable undefined <----- ERROR
$q->on('product_products.id', '=', 'product_translations.product_id')->where('product_translations.locale', '=', 'de');
})->select('product_products.*')->orderBy('product_translations.name');
}
Upvotes: 1
Views: 681
Reputation: 13313
You need to use use
keyword:
return $query->join('product_translations', function($q) use ($sort_dir)
Explanation:
This is an anonymous function. So, the variable loses its scope inside that function. You need to make the variable available for that function using use
in PHP
Upvotes: 8
Reputation: 1048
If you want to use variables which within your function, which is another scope than where the variable is defined, you have to use a use
statement:
return $query->join('product_translations', function($q) use ($sort_dir)
Upvotes: 1
Reputation: 1935
You need to pass the parameters to the anonymous function, you are only passing $q
, any variable can't be seen inside the function unless it was passed to it using use($var)
Upvotes: 1