Home > Mobile >  Foreach loop does not add counter
Foreach loop does not add counter

Time:06-11

I have this custom foreach loop at Blade:

<div id="dynamic_field">
    @foreach($niloufars as $niloufar)
        @php 
            $counter = 1;
        @endphp 
        <div >
            <div >
                <div >
                    <span ></span>
                    <label for="niloufar_name">Title</label>
                    <input type="text"
                        
                        name="niloufar_name_{{ $counter }}" value="{{ $niloufar->name }}">
                </div>
            </div>
            <div >
                <div >
                    <span ></span>
                    <label for="niloufar_link">Link</label>
                    <input type="text"
                        
                        name="niloufar_link_{{ $counter }}" value="{{ $niloufar->link }}">
                </div>
            </div>
        </div>  
        @php
            $counter = $counter   1;
        @endphp
    @endforeach
</div>

So as you can see I have set a $counter variable set to 1 at the 1st iteration and then I add 1 to it so that for the next iteration it will be 2.

Therefore I can set unique names for form fields in order for further process.

But the problem with this is that, the variable is just set to 1 the whole time:

     <div >
        <div >
            <div >
                <span ></span>
                <label for="niloufar_name">Title</label>
                <input type="text"
                    
                    name="niloufar_name_1" value="">
            </div>
        </div>
        <div >
            <div >
                <span ></span>
                <label for="niloufar_link">Link</label>
                <input type="text"
                    
                    name="niloufar_link_1" value="">
            </div>
        </div>
    </div>  
                         
    <div >
        <div >
            <div >
                <span ></span>
                <label for="niloufar_name">Title</label>
                <input type="text"
                    
                    name="niloufar_name_1" value="">
            </div>
        </div>
        <div >
            <div >
                <span ></span>
                <label for="niloufar_link">Link</label>
                <input type="text"
                    
                    name="niloufar_link_1" value="">
            </div>
        </div>
    </div>  

So what's going wrong here? How can I show current iteration properly for each form field name?

CodePudding user response:

Move the setting of the counter before the foreach (as it is, you are setting it to 1 in the beginning of every loop):

@php 
    $counter = 1;
@endphp 
@foreach($niloufars as $niloufar)
        
  • Related