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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.