Blade Foreach: first/last item of the array

Blade templates are mostly for viewing data. But sometimes we do need to add some checks and IF-structures. One of the tricky examples – loop through @foreach but do some action only on first/last element of the array. Blade doesn’t have that functions in itself, so what do we do?

Under the hood, Blade files are actually transformed into plain PHP. So the trick here is that we can use pretty much any core PHP function we want. And with arrays we have two useful functions to get the first and last element of the array:

  • end($array) – advances array’s internal pointer to the last element, and returns its value.
  • reset($array) – rewinds array’s internal pointer to the first element and returns the value of the first array element.

So how does it look in actual Blade example? Let’s say we want to hide every div element except for the first one:

Want more articles like this every week? Subscribe!




Still not sure? Want to check out past newsletter issues?
Here they are – just click this link!

Similar example – what if we want to add a CSS class to the last menu item?

That’s it. As you can see, Blade is not only a template engine, it has all power of core PHP structures and functions.

Liked the article? Maybe you need help with your Laravel project?
Our LaravelDaily Team can help!

7 thoughts on “Blade Foreach: first/last item of the array

  1. Not the best solution in my opinion. What if your array looks like this: [1, 1, 2, 2] then it will not work. My suggestion: use an index and test against that variable:

    @foreach($array as $i => $item)
    @if($i == 0) first item @endif
    @if($i == count($array) – 1) last item @endif
    @endforeach

  2. What about this:

    @if ( $resultado != $resultados->last() )

    @endif

    You could get the last item of a collection, be the native method last()

  3. As for Laravel 5.3+, you can use the $loop variable
    @foreach($array as $i => $item)
    @if($loop->last) last item @endif
    @endforeach

Leave a Reply

Your email address will not be published. Required fields are marked *