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?

Update February 2018: In Laravel 5.3+ you can use $loop variable inside your blade loops. This variable holds useful information like current loop index and whether this is the first or last iteration through the loop.

This is how you check for the first item:

Similarly, we can check for the last item in the loop:

Older version of the article:

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.

Check out my new online course: Laravel Eloquent: Expert Level

8 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

  2. What about this:

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


    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

  4. Sir, please do help me i dont know how to create a controller using array_push and blade with forloop for showing the array value in the view page? I Would be greatefull if u help me please..

Leave a Reply

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