I have a function that imports an Excel with the Laravel-Excel library, and inside said function in the $sheet->each(function($row)) {} I am adding the records in an array that I have declared inside the function but outside of the $sheet->each(), the thing is that at the bottom of the function I can't use that array to make a return, it's as if it wasn't declared.
Do you know if there is any specific method or functionality of Laravel Excel to do it?
public function excel($code){
$i = 0;
$transact = array();
$file = File::find($code);
$url = $file->FILE_url;
Excel::selectSheetsByIndex(0)->load($url, function ($sheet) use($i, $transact){
$hoja->each(function ($row) use($i, $transact){
$inCode = $row['inCode'];
$prCode = $row['prCode'];
$transact[$i] = (int)$inCode;
$transact[$i] = (int)$prCode;
$i++;
});
return $transact;
});
}
In this way the $i does not autoincrement and I cannot return from $transact no matter how much I put global in front of it.
The problem is that the closure you are passing as a parameter has its own context, where variables passed through mediate
use
are passed by value and not by reference. This is why they are not modifiable.The way to modify these variables is to pass them by reference, using the modifier
&
:Edition:
I leave you an example code, so that you understand closures a little better:
Output:
It is important to note that an automatic binding of is made
$this
, so this property can be accessed without the need to indicate it in theuse
( read )I recommend you read Closures and Scopes .