Skip to main content
Tutorial Free

Did you know about Forelse loop in Blade?

July 11, 2016
1 min read
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?

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.