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:

@foreach ($menu as $item)
  <div @if ($loop->first) class="hidden" @endif>
    <h2>{{ $item->title }}</h2>
  </div>
@endforeach

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

@foreach ($menu as $item)
  <div @if ($loop->last) class="no_margin" @endif>
    <h2>{{ $item->title }}</h2>
  </div>
@endforeach

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:

@foreach ($menu as $item)
  <div @if ($item != reset($menu)) class="hidden" @endif>
    <h2>{{ $item->title }}</h2>
  </div>
@endforeach
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?

@foreach ($menu as $item)
  <div @if ($item == end($menu)) class="no_margin" @endif>
    <h2>{{ $item->title }}</h2>
  </div>
@endforeach

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses