Search code examples
phpexcellaravelfacade

Get total number of sheet in Laravel


I'm trying to get the total number of sheets present in an uploaded Excel file in Laravel. The file I'm uploading has 3 sheets. So I'm expecting to get an output of $counter = 3.

Code:

$counter=0;
Excel::load($fileDetails['file_path'], function($sheet) use($counter) {
    $sheet->each(function($sheet) use($counter) {
        echo "It works</br>";   
        $counter++;
    });
});
echo $counter; exit;

Output:

It works
It works
It works
0   //-- This is $counter, which is not get incremented. It has to be 3.

Solution

  • The use works like passing parameters. The default is to pass by value, so any modifications made inside the function will not be reflected outside the function's scope.

    If you pass the variable by reference, however, the changes will be reflected.

    Update your code to:

    $counter=0;
    // add & to have var passed by reference
    Excel::load($fileDetails['file_path'], function($sheet) use(&$counter) {
        // add & to have var passed by reference
        $sheet->each(function($sheet) use(&$counter) {
            echo "It works</br>"; 
            $counter++;
        });
    });
    echo $counter;
    exit;