Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query builder: passing argument to anonymous function

Tags:

php

laravel

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?

like image 298
Khanh Tran Avatar asked Feb 21 '13 16:02

Khanh Tran


1 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);
    });
....
}
like image 95
Aran Avatar answered Sep 25 '22 15:09

Aran