Introducing Laravel Quizzes! Play now

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

// Assume we are inside a <table>'s <tbody> element

@if ($users->count())
    @foreach($users as $user)
        <tr>
            <td>{{ $user->name }}</td>
            ...
        </tr>
    @endforeach
@else
    <tr><td colspan="...">No users found.</td></tr>
@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

// Assume we are inside a <table>'s <tbody> element

@forelse($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        ...
    </tr>
@empty
    <tr><td colspan="...">No users found.</td></tr>
@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.