0

I retrieve a laravel collection from a database on which I want to update certain values based on three calculations. But before I do the calculations I first check if all the relevant collection items is not null. I can check if they are null but for some reason cannot rerieve an error variable that has Controller function scope to tell a user that a variable has not been set.

$error_arr = [];
$calculation = FertilApp::calculation($product, $farm, $agent);
$calculation->each(function ($item, $key) {
    if ($item->ha === null) {
        $error_arr[] = 'Prices has been updated';
        $error_arr[] = 'But no calculation has been done, please update following block:' . $item->block;
        return false;
     }
});

The variable $error_arr returns an empty array even though I know the ha key is null. The alternative is to use a normal foreach() loop. I have tried it and it works, but I really want to know why this is not working.

Can someone please help to give me a clue to why this collection each() method is denying my variable access to values from outside the collection method?

EDIT: If I try to pass my variable as a parameter I get the following error message Cannot use a scalar value as an array.

Laravel version: 5.6.39

Hmerman6006
  • 1,622
  • 1
  • 20
  • 45

1 Answers1

1

Try a global statement:

$calculation->each(function ($item, $key) {
   global $error_arr;

$error_arr is empty in your code, because it doesn't exist in the scope of the callback function of your each method. Unlike other languages – like JavaScript – variables outside a function aren't accessible by default inside the function. See PHP's documentation on variable scope for details.

Lasse
  • 1,414
  • 11
  • 19
  • Thanks your solution works. I also had to add `global $error_arr` in front of the variable declaration of my Controller function. This was in the comment section in your link. This is due to the fact that `$calculation->each(function ($item, $key) {` is a child function of my Controller function. – Hmerman6006 Jan 01 '21 at 16:53