I got a problem in passing variable to query builder closure, here is my code:
function get_usersbyname($name){
dd($name);
$resultset = DB::table('users')->where(function($query){
$query->where('username', 'LIKE', $name);
});
....
}
if I run it, it returns an error "undefined name variable
", but I already passed $name
variable and checked its existence.
Also I cann't find any resouce explains how to pass variable to query builder anonymous function.
Could you help me with this problem?
You need to the tell the anonymous function to use that variable like...
Because that variable is outside the scope of the annonymous function it needs to be passed in using the use keyword as shown in the example below.
function get_usersbyname($name){
dd($name);
$resultset = DB::table('users')->where(function($query) use ($name) {
$query->where('username', 'LIKE', $name);
});
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With