skip to Main Content

Closure Variable Problem Access and replace

I’m having trouble using closure variables. When I declare $data as a collection and use chunk to read a file, I want to add each chunk to my data list. However, after the process is finished, when I check the variable, it’s empty (=[]). Can anyone help me? Here is my code

$data = collect();
            Excel::filter('chunk')->load($path)->chunk(100, function ($results) use (&$data) {
                foreach ($results as $row) {
                    $data = array_merge($data, [$results->toArray()]);
                }
                echo $results;
            }, true);
            dd($data);

2

Answers


  1. You have two options:

    $data = [];
    
    Excel::filter('chunk')->load($path)->chunk(100, function ($results) use (&$data) {
      foreach ($results as $row) {
        $data[] = $row;
      }
    }, true);
    
    dd(collect($data)); // assuming you need $data as a collection
    
    $data = collect([]);
    
    Excel::filter('chunk')->load($path)->chunk(100, function ($results) use ($data) {
      foreach ($results as $row) {
        $data->push($row);
      }
    }, true);
    
    dd($data);
    
    Login or Signup to reply.
  2. The problem with the code lies in how the $data variable is being handled within the chunk method. Initially, $data is correctly initialized as a collection, but within the chunk closure, it’s being redefined as an array using array_merge(). This inconsistency causes issues because collections and arrays are not interchangeable without proper conversion.

    Here’s a corrected version of the code:

    $data = collect();
    Excel::filter('chunk')->load($path)->chunk(100, function ($results) use (&$data) {
        foreach ($results as $row) {
            $data->push($row->toArray());
        }
    }, true);
    
    dd($data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search