Laravel Blade Conditional Statements


In Laravel Blade, the @if directive allows you to perform conditional rendering within your views. This means you can control which parts of your Blade templates are displayed based on certain conditions. The @if directive is part of Blade's control structures, which also include @elseif, @else, and @endif.

Here’s a detailed explanation of how to use the @if statement in Laravel Blade:

Basic Syntax

The basic syntax for the @if directive is:

@if (condition) // HTML or Blade syntax to render if condition is true @endif

Example:

@if ($user) <p>Welcome, {{ $user->name }}!</p> @else <p>Welcome, guest!</p> @endif

In this example:

  • If $user is not null or false, it will display the user’s name.
  • If $user is null or false, it will display "Welcome, guest!"

Using @elseif and @else

You can use @elseif and @else to handle multiple conditions.

Example:

@if ($user) <p>Welcome, {{ $user->name }}!</p> @elseif ($guest) <p>Welcome, {{ $guest->name }}!</p> @else <p>Welcome, visitor!</p> @endif

In this example:

  • If $user is true, it displays the user’s name.
  • If $user is false but $guest is true, it displays the guest’s name.
  • If neither $user nor $guest is true, it displays "Welcome, visitor!"

Using @isset and @empty

  • @isset: Checks if a variable is set and not null.

    Example:

    @isset($user) <p>User is set!</p> @endisset
  • @empty: Checks if a variable is empty. An empty variable is one that is null, false, or an empty string.

    Example:

    @empty($items) <p>No items available.</p> @endempty

Combining Conditions

You can combine conditions using logical operators like && (AND) and || (OR).

Example:

@if ($user && $user->isActive()) <p>Welcome back, {{ $user->name }}!</p> @else <p>Account not active or user not logged in.</p> @endif

Inline @if Statements

For simple conditions, you can use inline @if statements:

Example:

<p> @if ($isLoggedIn) Logged in @else Not logged in @endif </p>

Summary

The @if directive in Laravel Blade allows for conditional rendering of content based on certain conditions. It provides a clean and readable way to include logic in your views while keeping the template syntax concise and easy to understand. With @if, @elseif, @else, @isset, and @empty, you can handle a variety of conditional scenarios in your Blade templates.