Laravel if condition directive example

Laravel blade template provides directives for easy way to access PHP conditions, loops, statements etc. These structure provides easy way to access PHP structure.

In this post, we will see how you can write PHP if condition in Laravel blade template. You can create if condition using the @if, @elseif, @else, and @endif directives.

Example:

@if (count($user_address)) === 1)
    // there is one user address
@elseif (count($user_address) > 1)
    // there are more than one user addresses
@else
    // there is no any user address
@endif

In the other example, it is also used to print error or any message from session data. This is common way to print session data from controller to view.

Example:

@if (Session::has('error'))
    <div class="alert alert-danger" role="alert">{{ Session::get('error') }}</div>
@endif

@if (Session::has('success'))
    <div class="alert alert-success" role="alert">{{ Session::get('success') }}</div>
@endif

@if (Session::has('message'))
    <div class="alert alert-primary" role="alert">{{ Session::get('message') }}</div>
@endif

On the other way, there is also @unless directive which can be used for reverse if condition.

@unless (count($user_address)) > 0)
    // there is no any user address
@endunless

For additional way, there is also @isset directive available which works same as isset() method in PHP. This will check if the given variable is defined or not.

Example:

@isset($post)
    // $post is defined and is not null...
@endisset

On the other way, you can check if the given variable is empty or not with @empty directive. This works same as PHP empty() function.

@empty($post)
    // $post is empty
@endempty

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment