How to use the if-else blade condition if else in Laravel?

Laravel framework allows us to use blade directives in the Laravel blade files. This Laravel built-in and customized blade directives greatly simplify coding logic and help write simple and clean code. There are many blade directives handling loops and conditional statements. For example, we can use the if else blade condition to handle if-else conditional statements in Laravel. It will allow to conditional display content based on the conditions.

Use if else blade condition

A pretty straightforward and simple approach similar to the standard use of the conditional statement. We use the if and else blocks starting with an ‘@’ denoting it as a blade directive.

@if($user->status =='active')         
      <td>{{ $user->name }}</td>         
@else
      <td> Guest </td>        
@endif

The code snippet shows the use of an if-else blade condition. It creates a simple and clean workflow without the use of many brackets or nested structures. We can also add multiple if-else conditions as shown below.

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

The multiple conditions each check a case and then print the corresponding results accordingly.

With the use of @if, @else, and @elseif directives, we can easily create complex conditional statements in Laravel Blades. They allow you to conditionally display content based on various conditions and control the flow of your template rendering.

Leave a Comment