How to use the @forelse blade directive in Laravel

Blade directives are shortcut codes that help to implement basic PHP control structure. @forelse blade directive eases use of complex loop structures and conditional statements. It helps makes a code snippets clean and easier to understand.

Let us consider an example where forelse would work best, if you have to print a list of all student’s names. For this, you will have to run a loop. However you should first assure if the student exists then run the loop. You will normally prefer using the foreach blade directive and @if loop for this, as shown below.

@if($students->count() > 0)
    @foreach($students as $student)
        {{ $student->name }}
    No Students Found	

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

@forelse($students as $student)
    {{ $student->name }}
    No Students Found

A much simpler and cleaner code with a no nested brackets. Using foreach you had to add @if, @else, @foreach with multiple braces. Using @forelse simplifies the code where the @forelse directive is by default applicable only on the students that exist.

Customized directives like these make the coding logic much simpler. Most importantly, when you are working with long blocks of codes and multiple functions, directives like these help simplify the complex code structures. Moreover, embedding multi-logics in single directives they also optimize your code.

Leave a Comment