Laravel Blade @each

Tutorials

September 25th, 2014

blade-each.png

I’m sure you’ve been there. You need to loop a collection and either show the results or display a “no results” view.

A common way to approach this in Blade could be to do something like this:

1@if (count($records))
2 @foreach ($records as $record)
3 @include('record.item', $record)
4 @endforeach
5@else
6 @include('record.no-items')
7@endif

Sure that works but kind of gross with all the nesting and in the wild I’ve seen code like this become unwieldily. To help make this cleaner Blade includes an often overlooked @each() option. Here is how that same code could be rewritten.

1// record/list.blade.php
2<ul>
3 @each('record.item', $records, 'record', 'record.no-items')
4</ul>
5
6// record/item.blade.php
7<li>{{ $record->title }}</li>
8
9// record/no-items.blade.php
10<li>Sorry Charlie, No posts here.</li>

With that the view is now cleaner, easier to follow, and you will thank yourself later for setting it up this way.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.