I'm currently available for full time hire! Inquire Here

This post is more than a year old. There is a chance the content is outdated.

Using the @forelse blade directive

Using the @forelse blade directive


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.

Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.