Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

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 - 10,231 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

Authentication Log v6.0.0

We're excited to announce the release of Laravel Authentication Log v6.0.0! This major release brings significant improvements to security, user experience, and developer productivity. With support for Laravel 11.x and 12.x, enhanced suspicious activity detection, comprehensive session management, and numerous bug fixes, this release represents a substantial step forward for the package.

7 min read - 5,035 views -