Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel foreach variable loop scope

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 accessible outside endforeach loop after @endforeach

like image 485
Mayur Panchal Avatar asked Feb 26 '18 11:02

Mayur Panchal


1 Answers

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
like image 172
Alexey Mezenin Avatar answered Oct 21 '22 16:10

Alexey Mezenin