External variable in callback for chunk() 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-&gt;repository-&gt;searchInName($leads, $param));

            // search in email
            $results = array_merge($results, $this-&gt;repository-&gt;searchInEmail($leads, $param));

           // and so on ...
    }

    // eliminate duplicates
    $collection = collect($results);
    $collection = $collection-&gt;unique();

    $results = $collection-&gt;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 &amp; to $results).

Lead::chunk(100, function($leads) use (&amp;$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?
You managed to bypass the query builder, which could have implemented this as a trivial, single query on the backing database, and instead managed to emulate that query in an very inefficient manner yourself.

// get all leads
Lead::chunk(100, function($leads) use ($results, $param) {
    // search in name
    $results = array_merge($results, $this-&gt;repository-&gt;searchInName($leads, $param));

    // search in email
    $results = array_merge($results, $this-&gt;repository-&gt;searchInEmail($leads, $param));

    // and so on ...
}


This effectively causes 2 additional queries to the database for each 100 results in the Lead model. This might still work reasonably in your test environment where you have at most a few dozen leads registered, but will crawl to a halt in production as the number of leads increases with time.

Even worse, it requires you to stream all existing Lead instances through PHP, even if they are not even part of the final result set.