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.

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

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


No users found.

Nice, isn't it?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like