6

When I use Laravel blade file foreach loop, the variable is accessible after the foreach loop, whereas the scope of the variable should be only within the loop

@foreach($user->referral as $ref)
  <tr>
    <td>{{ $ref->referral_amount }}</td>
    <td>{{ $ref->status }}</td>
  </tr>
@endforeach

$ref: This variable is accessible outside endforeach loop after @endforeach

10
  • 2
    No dude you can't use $ref outside of loop. Commented Feb 26, 2018 at 11:13
  • 2
    It is accessible after the loop, tried it Commented Feb 26, 2018 at 11:18
  • 1
    No, the only reason that is possible is if you already send a $ref variable to your view from your controller/view-composer/.. Commented Feb 26, 2018 at 11:20
  • 2
    @Christophvh I tried a foreach, and didn't have that variable passed from the controller Commented Feb 26, 2018 at 11:21
  • 2
    I know it shouldn't be accessible, but I am able to access the variable outside the loop, no idea why @HirenGohel Commented Feb 26, 2018 at 11:32

3 Answers 3

7

From the foreach docs:

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()

So, if you want to destroy the reference, do this:

<?php unset($ref); ?>

Or:

@php unset($ref); @endphp
Sign up to request clarification or add additional context in comments.

Comments

3

It is recommended to destroy it by unset()

 @php unset($ref); @endphp

Comments

0

As per your problem you can use unset() method of php for destroy a variables.

For that you can use this type of code inside your blade file after foreach loop.

<?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
?>

or

@php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
@endphp

Comments

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.