I am trying to implement search in Laravel. I want to search on models. Since there can be many records in the database, I am trying the chunk function.public function searchLeads($param)    {        $results = array();        // get all leads        Lead::chunk(100, function($leads) use ($results, $param) {            // search in name            $results = array_merge($results, $this->repository->searchInName($leads, $param));            // search in email            $results = array_merge($results, $this->repository->searchInEmail($leads, $param));           // and so on ...    }    // eliminate duplicates    $collection = collect($results);    $collection = $collection->unique();    $results = $collection->all();    dd($results);    // return $results;}Note: The searchIn... functions return array of results and are working as expected.When I try the above code, I get an empty array. So I changed the following line (added a reference & to $results).Lead::chunk(100, function($leads) use (&$results, $param) {Now I get the expected output.Am I doing this the correct way? Have I stumbled upon the right solution, or am I missing something that might introduce bugs in the code?
External variable in callback for chunk()
php;laravel
I got the solution after reading a bit about php closures. My real worry was that I am not using the $results array correctly.But after reading php docs, I know I am doing it correctly.Please note that I am aware of where clause and it's usage would be much more efficient here. But that's not what I was trying to ask.