Using the @forelse blade directive

Use this nifty blade directive in place of a foreach inside an if/else.

AR
Anthony Rappa
1 min read - 5,423 views -

There are many great blade directives made available by the Laravel framework. Every new release I read the documentation in full to see if there are any cool new hidden features I can use.

One that I find useful a lot is the @forelse directive, and this is made specifically when you have a foreach loop inside a if/else statement.

As one example, I find them useful in rendering simple tables from models.

Without @forelse

1// Assume we are inside a <table>'s <tbody> element
2 
3@if ($users->count())
4 @foreach($users as $user)
5 <tr>
6 <td>{{ $user->name }}</td>
7 ...
8 </tr>
9 @endforeach
10@else
11 <tr><td colspan="...">No users found.</td></tr>
12@endif

There is nothing wrong with the above code at all, but if you're the type of person that likes to minimize directives and indenting as I do, then @forelse is a little more syntactically pleasing.

With @forelse

1// Assume we are inside a <table>'s <tbody> element
2 
3@forelse($users as $user)
4 <tr>
5 <td>{{ $user->name }}</td>
6 ...
7 </tr>
8@empty
9 <tr><td colspan="...">No users found.</td></tr>
10@endforelse

As you can see we removed the if directive and merged it with the foreach. We then use the @empty directive to act as the else when there are not items to iterate through.

Read next