Laravel Blade: Increment variable by 1 each time?

I'll-Be-Back picture I'll-Be-Back · Jun 18, 2015 · Viewed 36.8k times · Source

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

Limon Monte picture Limon Monte · Jun 18, 2015

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.