Did you know about Forelse loop in Blade?

As a tradition of posting little things here on the blog, one more useful detail. What do you do when you need to show a loop in Blade with foreach, but the list might be empty? You probably write if-else statement around it, right? what-if-i-told-you There's a "magic" loop structure called forelse. Here's how it works. Instead of:
@if ($users->count())
  @foreach ($users as $user)
    

This is user {{ $user->id }}

@endforeach @else

No users found.

@endif
You can use this:
@forelse ($users as $user)
    

This is user {{ $user->id }}

@empty

No users found.

@endforelse
Nice, isn't it?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 89 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses