I'll-Be-Back I'll-Be-Back - 29 days ago 7
PHP Question

Laravel Blade: Increment variable by 1 each time?

Using Laravel blade template, is there a way to include a variable and increase each time in the foreach or what is better approach?

For example:

@foreach($categories as $category)
<li><a href="#tab_c1" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach


In the
foreach
block, the value from #tab_c1 will need to be increase. eg:
#tab_c1, #tab_c2, #tab_c3

Answer

Add iterator to @foreach:

@foreach($categories as $key => $category)
  <li @if ($key === 0) class="active" @endif>
    <a href="#tab_c{{$key+1}}" role="tab" data-toggle="tab">
      {{$category->name}}
    </a>
  </li>
@endforeach

{{$key+1}} in my example because in PHP iterator starts at 0.

Comments