Rohan Shewale's Blog

Forelse loop in Blade - Laravel

July 22, 2017 | 0 Minute Read

Blade – a simple, yet powerful templating engine, provided with Laravel, is quite good in keeping the view clean when populating with dynamic data. Among various useful directives, loops are one of the most commonly used ones, of which forelse is the one I recently discovered, almost by mistake (thanks to atom’s Laravel snippet plugin) while typing some internal CSS during a quick-fix.

Sometimes after passing the fetched collection to view, there is a possibility that the list might be empty, and we wrap the loop inside a if-else condition block, like —


@if ($posts->count())
  @foreach($posts as $post)
    <h5>{{ $post->title }}</h5>
  @endforeach
@else
  <p>There are no more post</p>
@endif

Instead, we can use the forelse in the situation as —


@forelse($posts as $post)
  <h5>{{ $post->title }}</h5>
@empty
  <p>There are no more post</p>
@endforelse

Pretty neat. Forelse loop is hinted in the Laravel docs[1] but no specific description in provided (Nor was I able to locate it at Laravel’s API documentation).