Hello.

There is a code that displays all the elements from the database, during the output checks for the presence of a value in the database:

<div class="tickets-places"> {{$i = 1}} @foreach($tickets as $t) @if($t->number != $i) <div class="one-place" id="game-place-{{$i}}" onclick="setplace(2,1, {{$i}}, {{$user->id}});"> <span>{{$i}}</span> </div> @else <div class="one-place" id="game-place-" onclick="setplace(2,1, {{$i}}, {{$user->id}});"> <span>test</span> </div> @endif {{$i = $i+1}} @endforeach </div> 

If the value is in the database, then displays test. It turns out that if @if works, then it changes the first elements or if the value of $t->number is set in two lines in the database, it still displays test only for the first value. How can this be solved?

    2 answers 2

    To get the current index when traversing an array, better use the $loop variable here an article will help you with it https://mattstauffer.co/blog/the-new-loop-variable-in-laravel-5-3

    on your problem, I think this is due to the fact that you always have $i before the start of the cycle. I can’t be more precise, because I don’t know that when iterating a cycle in the $t->number variable

      Your option:

       <div class="tickets-places"> @php $i = 1; @endphp @foreach($tickets as $t) @if($t->number != $i) <div class="one-place" id="game-place-{{$i}}" onclick="setplace(2,1, {{$i}}, {{$user->id}});"> <span>{{$i}}</span> </div> @else <div class="one-place" id="game-place-" onclick="setplace(2,1, {{$i}}, {{$user->id}});"> <span>test</span> </div> @endif @php $i += 1; @endphp @endforeach </div> 

      But it is better to test this option:

       <div class="tickets-places"> @foreach($tickets as $t) @if($t->number != $loop->iteration) <div class="one-place" id="game-place-{{ $loop->iteration }}" onclick="setplace(2,1, {{ $loop->iteration }}, {{ $user->id }});"> <span>{{ $loop->iteration }}</span> </div> @else <div class="one-place" id="game-place-" onclick="setplace(2,1, {{ $loop->iteration }}, {{ $user->id }});"> <span>test</span> </div> @endif @endforeach 

      ps if your $t->number starts with 1 use $loop->iteration if with 0 then $loop->index