Laravel Blade: Increment variable by 1 each time?

49,715

Solution 1

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.

Solution 2

In Laravel 5.3 you can use The Loop Variable, $loop->iteration for concrete situation. https://laravel.com/docs/5.3/blade#the-loop-variable

Exapmle:

@foreach ($questions as $question)
    <tr>
        <th scope="row">{{ $loop->iteration }}</th>
        <td>{{ $question->question }}</td>
        <td>{{ $question->category_id }}</td>
    </tr>
@endforeach

Solution 3

Add a key value in the foreach loop

@foreach($questions as $key => $question)
<tr>
    <th scope="row">{{ ++$key }}</th>
    <td>{{ $question->question }}</td>
    <td>{{ $question->category_id }}</td>
</tr>
@endforeach

Solution 4

Just use {{ $loop->iteration }} to iterate from 1 to limit

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

Solution 5

You can try this:

@php($count=0)

@foreach($unit->materials as $m)
    @if($m->type == "videos")
        @php($count++)
    @endif
@endforeach

{{$count}}
Share:
49,715
I'll-Be-Back
Author by

I'll-Be-Back

Updated on November 11, 2020

Comments

  • I'll-Be-Back
    I'll-Be-Back over 3 years

    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