3

I need to know if there is a laravel blade way to do the following without using PHP tags.

<?php $i = 1; ?>
@foreach($rows as $row)
   //do something
   <?php $i++; ?>
@endforeach

As you can see the code looks ugly with tags and its time wasting to write extra tags.

1

3 Answers 3

6

use index

@foreach($rows as $index=>$row)
  {{$index}}
@endforeach

if you want to define some variable then use @php($counter=0)

 @php($counter=0)
 @foreach($rows as $index=>$row)
      $counter=$counter+2;
      {{$counter}}
 @endforeach
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I don't like the php key, its still in your answer. By the way I accepted the @adnan's answer which is more precise and to the point. I give you 1 upvote
3

If you are using laravel > 5.4 then you can use $loop variable to get the index.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

Similarly, you can apply no need to reinvent the wheel.

@foreach($rows as $row)
   //do something

 {{ $loop->index }} 
@endforeac

hope this helps

6 Comments

I don't think he needs something with first or last loop.
@AshutoshSharma this is just an example.
@AdnanMumtaz you are real champ. Thanks for your answer its working for me, both the solution you have provided.
@TahirAfridi but you need incremental $i after foreach loop then?
@JinalSomaiya {{ $loop->index }} is available in inside a foreach loop you can explore the docs
|
2

Try this $loop->iteration

 @foreach($rows as $row)
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ $row->item1}}</td>
                <td>{{ $row->item2}}</td>
            </tr>
 @endforeach

The result will be like this

---------------------------------
Si#     |    item 1    |  item2 |
---------------------------------
1       |    AAA       |  111   |
2       |    BBB       |  222   |
---------------------------------

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.