Dev Leak
Press ( / )
Subscribe Sign In
home Home popular Popular topics Topics mail Newsletter
Topic: Laravel Laravel Topic: Animation Animation Topic: Docker Docker Topic: Fundamentals Fundamentals Topic: Debugging Debugging Topic: Web Web
home Home popular Popular topics Topics mail Newsletter
Topic: Laravel Topic: Animation Topic: Docker Topic: Fundamentals Topic: Debugging Topic: Web
3 Examples of When to Use @unless
5 min read

3 Examples of When to Use @unless

When to use the @unless directive in Laravel's Blade Templates with three examples.

April 5, 2023

1k Views
david

david

20 Posts

mail-dark Newsletter

3 Examples of When to Use @unless

When to use the @unless directive in Laravel's Blade Templates with three examples.

david

david

20 Posts

mail-dark Newsletter

April 5, 2023

1k Views

Say Thanks

Buy a Thanks, and directly support content like this.

Card Information

check-green Thank you for supporting! A receipt will be sent to your email

Blade, the powerful and simple templating engine in Laravel, provides many directives that make creating clean and maintainable code in your web applications easy. Among these directives, the @unless directive is lesser-known but highly useful. It allows executing a block of code unless a given condition is true.

What is @unless

The @unless directive is a feature in Laravel's Blade templating engine that helps you write cleaner and more readable code. It's used to conditionally execute a block of code only if a specified condition is not true.

@unless is the inverse of the @if directive

When you use the @unless directive, you start by writing @unless(condition) followed by the block of code you want to execute if the condition is false. You can also include an @else block, which will be executed if the condition is true. To close the directive, you use @endunless.

@unless($loggedIn)
    <button>Login</button>
@else
    <p>Welcome, user!</p>
@endunless

In this example, the "Login" button will be displayed when $loggedIn is false, and the "Welcome, user!" message will be displayed when $loggedIn is true.

Under the Hood: How does it work?

The function that powers the @unless directive is found in the Illuminate\View\Compilers\Concerns\CompilesConditionals trait as part of the Blade template engine in Laravel. It compiles the @unless directive into its raw PHP equivalent, which the server can execute. This function converts Blade syntax into PHP code to be processed and rendered as HTML.

The underlying function looks like this:

/**
 * Compile the unless statements into valid PHP.
 *
 * @param  string  $expression
 * @return string
 */
protected function compileUnless($expression)
{
    return "<?php if (! {$expression}): ?>";
}

Here's a breakdown of the function:

  1. protected function compileUnless($expression): This line defines the function compileUnless with a single parameter, $expression.

  2. return "<?php if (! {$expression}): ?>";:  This line returns a PHP code snippet as a string. The snippet is an if statement that checks for the negation of $expression. The ! symbol is used for negation in PHP, so the code ! {$expression} means "if the expression is NOT true."

It is also to see how similar the @if directive is:

/**
 * Compile the if statements into valid PHP.
 *
 * @param  string  $expression
 * @return string
 */
protected function compileIf($expression)
{
    return "<?php if{$expression}: ?>";
}

Notice the absence of the ! in the return;

Example 1: Displaying a "No Results Found" Message

One everyday use case for the @unless directive is displaying a message when a search or query returns no results. In this scenario, you can use the @unless directive to check if the results collection is empty.

@unless($results->isEmpty())
    <ul>
        @foreach($results as $result)
            <li>{{ $result->name }}</li>
        @endforeach
    </ul>
@else
    <p>No results found.</p>
@endunless

In this example, the results list will be displayed if the $results collection is not empty. If the collection is empty, the "No results found." message will be shown instead.

Example 2: Hiding a Navigation Item for Unauthenticated Users

Another scenario where the @unless directive can be helpful is hiding a specific navigation item, such as a user's profile, for unauthenticated users. You can achieve this using the @unless directive to check if the user is authenticated.

<ul class="nav">
    <li><a href="/">Home</a></li>
    @unless(Auth::check())
        <li><a href="/login">Login</a></li>
        <li><a href="/register">Register</a></li>
    @else
        <li><a href="/profile">{{ Auth::user()->name }}</a></li>
        <li><a href="/logout">Logout</a></li>
    @endunless
</ul>

In this example, the "Login" and "Register" navigation items are displayed only if the user is not authenticated. If the user is authenticated, their profile and a "Logout" option are shown instead.

Example 3: Disabling a Button Based on User Permissions

The @unless directive can also be helpful in cases where you need to disable a button or action based on user permissions. For instance, you may want to disable the "Delete" button for users without the correct permissions.

@unless($user->can('delete', $item))
    <button type="button" class="btn btn-danger" disabled>Delete</button>
@else
    <form method="POST" action="{{ route('item.delete', $item->id) }}">
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-danger">Delete</button>
    </form>
@endunless

In this example, the "Delete" button is disabled for users who do not have the "delete" permission on the $item object. If the user has the required permission, they will see an enabled "Delete" button that submits the form.

Wrap-up

The @unless directive in Blade templates offers an elegant way to handle scenarios where you want to execute a block of code only if a given condition is false. Using this directive in your Laravel applications lets you write cleaner and more maintainable code, leading to a better overall development experience.

unlocked-white Subscribe for exclusive content
Run Laravel Sail in PhpStorm Run Laravel Sail in PhpStorm
1 min

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Run Laravel Sail in PhpStorm
2 min

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Fixing Permission Errors with Laravel Sail
1 min

Fixing Permission Errors with Laravel Sail

david

2k Views 2 years ago

Five Clever Ways to Use the chunk Method
11 min

Five Clever Ways to Use the chunk Method

david

2k Views 2 years ago

Using Macros to Simplify Migrations
2 min

Using Macros to Simplify Migrations

david

1k Views 2 years ago

Run PhpUnit in PhpStorm Run PhpUnit in PhpStorm
1 min

Run PhpUnit in PhpStorm

david

1k Views 2 years ago

A String Helper for Apostrophes
2 min

A String Helper for Apostrophes

david

1k Views 2 years ago

When to Use chunkWhile(): 5 examples
14 min

When to Use chunkWhile(): 5 examples

david

1k Views 2 years ago

Getting Started With Laravel and WSL2
2 min

Getting Started With Laravel and WSL2

david

1k Views 2 years ago

Five Ways to Use the Reject Method
10 min

Five Ways to Use the Reject Method

david

1k Views 2 years ago

Blade Templates | All the Ways to Pass Data to views
9 min

Blade Templates | All the Ways to Pass Data to views

david

1k Views 2 years ago

Five Smart Ways to Use Collapse
11 min

Five Smart Ways to Use Collapse

david

1k Views 2 years ago

Choose your Sail Services
1 min

Choose your Sail Services

david

1k Views 2 years ago

A String Helper For Estimating Read Time
2 min

A String Helper For Estimating Read Time

david

1k Views 2 years ago

Setup PHPUnit in PhpStorm for a Laravel Project
1 min

Setup PHPUnit in PhpStorm for a Laravel Project

david

1k Views 2 years ago

5 Powerful Ways to Use the all() method
9 min

5 Powerful Ways to Use the all() method

david

1k Views 2 years ago

Five Ways to Use the Combine Method
11 min

Five Ways to Use the Combine Method

david

1k Views 2 years ago

WhereLikeIn() Helper
6 min

WhereLikeIn() Helper

Tricia Blosser

977 Views 1 year ago

Related

Run Laravel Sail in PhpStorm Run Laravel Sail in PhpStorm
1 min

Run Laravel Sail in PhpStorm

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Topics

Laravel Animation
Run Laravel Sail in PhpStorm
2 min

Run Laravel Sail in PhpStorm

Streamlining Development with PhpStorm: Use your IDE to run Laravel Sail for a better experience.

david

2k Views 2 years ago

Topics

Laravel
Fixing Permission Errors with Laravel Sail
1 min

Fixing Permission Errors with Laravel Sail

Avoid Common Permission Errors with Laravel Sail

david

2k Views 2 years ago

Topics

Laravel Debugging
Five Clever Ways to Use the chunk Method
11 min

Five Clever Ways to Use the chunk Method

Harnessing the Power of the chunk() Method for Efficient Data Manipulation in Laravel Collections

david

2k Views 2 years ago

Topics

Laravel
Using Macros to Simplify Migrations
2 min

Using Macros to Simplify Migrations

How to add helper methods to the Blueprint Facade.

david

1k Views 2 years ago

Topics

Laravel
Run PhpUnit in PhpStorm Run PhpUnit in PhpStorm
1 min

Run PhpUnit in PhpStorm

david

1k Views 2 years ago

Topics

Laravel Animation
A String Helper for Apostrophes
2 min

A String Helper for Apostrophes

Effortlessly Converting Words to Possessive Forms with Laravel's String Class

david

1k Views 2 years ago

Topics

Laravel
When to Use chunkWhile(): 5 examples
14 min

When to Use chunkWhile(): 5 examples

Mastering the ChunkWhile Method in Laravel Collections: 5 Practical Examples

david

1k Views 2 years ago

Topics

Laravel
Getting Started With Laravel and WSL2
2 min

Getting Started With Laravel and WSL2

Simplifying Laravel Development on Windows with WSL2 and Laravel Sail

david

1k Views 2 years ago

Topics

Laravel Docker Fundamentals
Five Ways to Use the Reject Method
10 min

Five Ways to Use the Reject Method

Leveraging the Power of Laravel Collections: 5 Practical Applications of the 'Reject' Method

david

1k Views 2 years ago

Topics

Laravel
Blade Templates | All the Ways to Pass Data to views
9 min

Blade Templates | All the Ways to Pass Data to views

All the ways to pass data to Laravel Blade Templates: A comprehensive guide

david

1k Views 2 years ago

Topics

Laravel
Five Smart Ways to Use Collapse
11 min

Five Smart Ways to Use Collapse

Smart Ways to use the Collapse Method in Laravel Collections: 5 Practical Examples

david

1k Views 2 years ago

Topics

Laravel
Choose your Sail Services
1 min

Choose your Sail Services

Customizing Your Laravel Application with Sail: Selecting and Configuring Services for Your Docker-Compose File

david

1k Views 2 years ago

Topics

Laravel
A String Helper For Estimating Read Time
2 min

A String Helper For Estimating Read Time

Enhancing User Experience with a Custom Reading Time Estimator in Laravel

david

1k Views 2 years ago

Topics

Laravel
Setup PHPUnit in PhpStorm for a Laravel Project
1 min

Setup PHPUnit in PhpStorm for a Laravel Project

Setup PHPUnit in PhpStorm for a Laravel Project

david

1k Views 2 years ago

Topics

Laravel
5 Powerful Ways to Use the all() method
9 min

5 Powerful Ways to Use the all() method

Harnessing the Power of the all() Method for Efficient Data Manipulation in Laravel Collections

david

1k Views 2 years ago

Topics

Laravel
Five Ways to Use the Combine Method
11 min

Five Ways to Use the Combine Method

Leveraging the Power of Laravel Collections: 5 Neat Ways to Use the 'Combine' Method

david

1k Views 2 years ago

Topics

Laravel
WhereLikeIn() Helper
6 min

WhereLikeIn() Helper

Create a macro that loops through columns and search term strings on a Database Eloquent Builder.

Tricia Blosser

977 Views 1 year ago

Topics

Laravel
popular Popular topics Topics mail Newsletter

Footer

Dev Leak

Membership

  • Login
  • Newsletter
  • Subscribe

Support

  • Contact

Pages

  • Home
  • Search
  • Popular
  • Topics

Legal

  • Privacy Policy
  • Terms of Service

© 2025 DevLeak. All rights reserved.