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 ViewsBlade, 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:
-
protected function compileUnless($expression)
: This line defines the functioncompileUnless
with a single parameter,$expression
. -
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.