What is forelse loops in Laravel blade?


Besides 'foreach' loops, we also got 'forelse' loops in laravel blade template, what exactly this 'forelse' loops does? and most importantly should we care about it?

The 'forelse' loops is the better version of 'foreach', so yes, you should care, 'forelse' loops works exactly as 'foreach' except it also check the value is empty or not.

So with 'foreach' normally you check first whether the value is empty or not using 'if' statement, using 'forelse' you don't need to do that, the value is automatically checked.

Here's an example of 'foreach' loops
@if ($users->count())
  @foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
  @endforeach
@else
  <p>No users found.</p>
@endif

And here's the exact same loops using 'forelse'
@forelse ($users as $user)
    <p>This is user {{ $user->id }}</p>
@empty
    <p>No users found.</p>
@endforelse

The bottom line is, 'forelse' loops can simplify your code.


EmoticonEmoticon