How to use the @forelse blade directive in Laravel

Laravel’s Blade template provides us with a set of blade directives that simplifies the code and eases basic coding logic. The @forelse blade directive is one such that is specifically designed to handle empty arrays. Its use eases using complex loop structures and conditional statements. Thereby making the code easier and cleaner to read and understand. The directive is useful when we want to add special content in cases there are no items in the loop. Let us go through the simple steps on how to use this directive in a Laravel blade file.

Open the @forelse block and pass the array you want to iterate over. Consider the code snippet below.

@forelse ($posts as $post)
    
    <p>This is the post date {{ $post->date}}</p>

@empty
    
    <p>No posts found</p>

@endforelse

The logic works similarly to using an if condition and a for loop. When we iterate over an array if it has any number of elements. Consider the code snippet below.

@if($cars->count() > 0)
    @foreach($cars as $car)
        {{ $car->model }}
    @endforeach
@else
    No Cars Found	
@endif

However, to simplify the code even further and make it more straightforward, you should make use of the @forelse blade directive in cases like these as shown below.

It first checks the student’s count, if it is greater than 0, i.e. not empty, then it calls the foreach loop over the student’s array and prints the results accordingly. The @forelse directive works in the exact same way but with fewer lines of code and simple and clean logic.

@forelse($cars as $car)
    {{ $car->model }}
@empty
    No Cars Found
@endforelse

The code above is much simple with no nested brackets. The use of @forelse handles three blade directives, i.e. @if, @else, and @foreach, all in one.

Using @forelse helps handle empty arrays better and display custom content when there are no other items in a loop. These are more helpful when working with complex coding logic, multiple features, and long blocks of code. Moreover, embedding logic of multiple other directives in one, the single @forelse directive greatly optimizes the code.