Name a given id field inside a @foreach

Asked

Viewed 68 times

0

<?php counter = 0 ?>
@foreach($buildings as $building)
  <?php
    $var1 = counter;
    $counter = counter + 1;
  ?>
  <input type="checkbox" 
         id="campo{{counter}}"
         name="campo{{counter}}><td>{{$name_building}}</td>
  <br />
@endforeach

How do we fix this? If you have two items inside foreach, should look like this

<input type="checkbox" id=campo1 name=campo1...
<input type="checkbox" id=campo2 name=campo2...

How I assign a field within a foreach within the HTML?

  • I don’t quite understand, what you wish to do ???

  • Virgilio Novic: I need to name the input...put the id with the name that comes within the foreach...field type[1] field[2] field[3]... but this html does not allow, so how should I do? for each checkbox field should have a different name and how to do this?

  • Basically: <input type="checkbox" value="{{$nome do campo}}">!

  • right, but I don’t need value, I need the field id, I’ll improve the question...

  • Basically: <input type="checkbox" id="{{$nome do campo}}"> just put the field and value inside!

  • id="field{counter}}" and counter being a counter inside the foreach and what I’m trying now...thanks for so far!

  • 1

    Solved! Thank you!

Show 2 more comments

1 answer

1


Utilize $loop->iteration which will make available the position of each item of that foreach, example:

@foreach($buildings as $building)
  <input type="checkbox" 
         id="campo{{ $loop->iteration }}"
         name="campo{{ $loop->iteration }}><td>{{$name_building}}</td>
  <br />
@endforeach

this feature is from the Laravel 5.3 and helps in your doubt.


If the version is below Laravel 5.3 do so:

@foreach($buildings as $index => $building)
  <input type="checkbox" 
         id="campo{{ $index + 1 }}"
         name="campo{{ $index + 1 }}><td>{{$name_building}}</td>
  <br />
@endforeach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.