Cleaner Loops With Laravel's Forelse Directive

December 30th, 2023 • 1 minute read time

If you're wrapping foreach loops around if statements in Blade, here's a much cleaner way to achieve the same thing with a single directive.

Here's the way you might be writing conditional foreach statements right now.

@if (count($users))
    @foreach ($users as $user)
        <div>Details about {{ $user->name }}</div>
    @endforeach
@else
    <div>There are no users</div>
@endif

There's absolutely nothing wrong with this and in fact, it reads perfectly well — we're used to this sort of thing in PHP.

However, a shorter and cleaner syntax (in my opinion) is the forelse directive. It combines a foreach with an else, where you can display a placeholder for any empty content.

Here's what it looks like.

@forelse ($users as $user)
    <div>Details about {{ $user->name }}</div>
@empty
    <div>There are no users</div>
@endforelse

I've noticed complaints about the confusion around the term forelse but to be honest, looking at the syntax makes it pretty clear what's happening.

So, that's the forelse directive. Less typing, and cleaner blade templates!

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under