Surfe.be - passive income

Forelse loop in Laravel Blade

For-else Loop

What do you do when you need to show a loop in laravel blade with foreach , but the list might be empty ? You probably use if-else statement around it,right? There is a magic loop structure called forelse. here is 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

Hope you will like it.

Leave a comments

LET'S SOCIALITE

Recent Tweets