How to check if a variable is set and not empty in Laravel?

There are several ways to check if a variable is set and not empty in Laravel. Let’s check some examples to check if a variable exists using the @empty, @notEmpty, @isset, and @if directives to check if a variable.

Method 1 – empty and not Empty directives

We can apply the @notEmpty directive on a variable. This checks if the variable is is not empty. However, you may also use the @empty directive and pop up relevant error messages, in case if a variable is empty.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Blade Check If Variable Exists or Not Example - scratchcoding.dev</title>
</head>
<body>
    
@notEmpty($customers);

@empty($customers)
  <p> The variable customers is empty</p>
@endempty
    
</body>
</html>

Method 2 – is set directive

You can use the @isset directive in a Laravel blade file. This assures that a variable if already set and not empty. You may use this method before calling the variable to display results. This assures that the variable only shows up if it has set some value and is not null.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Blade Check If Variable Exists or Not Example - scratchcoding.dev</title>
</head>
<body>
    
@isset($customers)
    {{ $customers}}
@endisset
    
</body>
</html>

Method 3 – if directive

We can apply the @if directive with an isset function on the variable to examine. As shown below. The directive and function used both check if the variable is set and only then displays it.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Blade Check If Variable Exists or Not Example - scratchcoding.dev</title>
</head>
<body>
    
@if(isset($customers))
    {{ $customers}}
@endif
    
</body>
</html>

Method 4 – without directives

If you are new to Laravel, and don’t want to use any directive. However, your application goes to error state when an empty or not set variable pops up.

In this case you can use the code snippet below.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Blade Check If Variable Exists or Not Example - scratchcoding.dev</title>
</head>
<body>
    
{{ $customer ?? '' }}
    
</body>
</html>

This prints the value if a variable is set and not empty. Otherwise it prints empty. This is to avoid errors and exceptions in the application without using a directive.

Leave a Comment