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?

Like our articles?
Check out our Laravel online courses!

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here