For Else Loop in Laravel

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 it will help you.

Codechief is a very fast growing community among programmers and have a reach of around 1 million+ readers globally. Contribution at Codechief is open for all those who have a passion to learn and help others by sharing their knowledge. If you think you have the zeal to learn, start contributing on Codechief contribute. you can also mail your article to [email protected] See your article appearing on the codechief main page and help other code.

We believe that everyone has the right to learn, so we allow both students and professionals to contribute on Codechief.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website