6

In my blade code, I need a counter, to give divs that are rendered by a foreach loop unique id's. For that purpose I created a variable in my blade template like this:

{{ $counter = 0 }}

I use it in the html by just outputting it with {{ $counter = 0 }}

and the later on, I increment it like this: {{ $counter++ }}

It all works like a charm, except that at {{ $counter++ }} it's not only incrementing the variable, it's also outputting it to the view.

is there any way to prevent this?

ErikL
  • 2,031
  • 6
  • 34
  • 57
  • In Laravel 5.3 `@if($loop->first) Do something on the first iteration. @endif @if($loop->last) Do something on the last iteration. @endif` – Ilya Yaremchuk Jul 18 '16 at 17:51
  • 1
    that's a cool feature, but I actually need a number for each item in the array, not only the fist and last. I couldn't find a lot of documentation about the loop variable, any idea if it contains more than first and last? – ErikL Jul 18 '16 at 17:54
  • 1
    Bad but a working version `` – Ilya Yaremchuk Jul 18 '16 at 17:57
  • you can extend Blade. see here: http://stackoverflow.com/a/13019365/844726 – swatkins Jul 18 '16 at 18:14
  • Blade doesn't have a method for defining/modifying a PHP variable; you either need to extend Blade's functionality to handle that, or simply use a `` block. – Tim Lewis Mar 13 '17 at 15:06
  • @ErikL Why don't use: `foreach ($variable as $key => $value) { # code... }` where $key is the position number ? ;) – Troyer Mar 13 '17 at 15:20

2 Answers2

8

At first adding logic on blade templating is a bad practice, but sometimes we are forced to do, in that case you can just use PHP tags for it like this:

<?php $counter++; ?>

Another way to do it on Laravel 5.4 as docs indicate:

In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

@php
   $counter++;
@endphp

If you have your positions on the array keys you can use it on the @foreach like this:

@foreach ($variable as $key => $value) 
    //current position = $key
    # code...
@endforeach
Troyer
  • 6,765
  • 3
  • 34
  • 62
0

I use this extension do set variables on blade: https://github.com/RobinRadic/blade-extensions

You can use simple as @set($count, 1) or any value you want.