Laravel Blade If Condition Example

  2203 views   1 year ago Laravel

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.


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

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.


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

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

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

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

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.


    // $post is defined and is not null...

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.

    // $post is empty


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]