Home » Php » php – Query builder: passing argument to anonymous function

php – Query builder: passing argument to anonymous function

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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);
    });
....
}