M Biniek
M Biniek

Reputation: 63

Getting Laravel Excel chunk results outside callback

I have a problem with getting results of Laravel Excel chunk method outside callback. I tried to solve this problem by passing variable to callback by use keyword.

Guided by documentation I tried:

$foo = [[1, 2], [3, 4]];
Excel::filter('chunk')->load('file.csv')->chunk(250, function($results) use(&$foo)
{
        foreach($results as $row)
        {
            $foo[] = [$row[0], $row[1]];
            var_dump($foo); // [[1, 2], [3, 4], [5, 6]]
        }
});
var_dump($foo); // [[1, 2], [3, 4]]

$foo is passed by reference so I should be able to modify it inside my callback. Problem is, that in last var_dump() my $foo has same values as in the beginning. It is changing only inside the callback.

The only solution I found to be working is passing false as third argument to chunk() function, but that means I will not be able to use queue. It seems that my callback is somehow serialized and I am not able to pass my $foo by reference.

So my question is: how to get $results values to be outside callback?

Upvotes: 4

Views: 2124

Answers (1)

Osmel Pérez
Osmel Pérez

Reputation: 76

When using chunk, you are executing every chunk sandboxed, because the chunk is put on the queue (when no queue driver used, it uses the laravel sync driver). This means it's not possible to pass variables by reference.

This feature was added to 2.1.0 to tackle performance issues. The 3rd parameter of chunk() accepts a boolean to enable/disable this functionality. Reference: https://github.com/Maatwebsite/Laravel-Excel/issues/744

Upvotes: 1

Related Questions