Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Check unless condition in custom if blade directive in Laravel

Laravel’s Blade::if() method already comes with the following directives in order to check various conditions in blade template files.

  • @custom - Checks positive if condition
  • @elsecustom - Checks elseif condition
  • @endcustom - endif condition

So, for instance, if you want to check conditions on the env variables in the blade file, you could do like so.

@env('local')
    // The application is in the local environment...
@elseenv('testing')
    // The application is in the testing environment...
@else
    // The application is not in the local or testing environment...
@endenv

Now, if you want to check if something should render only when the application in the “production” mode, you could do like so.

@env('production')
@else
    // The application is not in the production environment...
@endenv

As you can see, here in this case, we’re using an empty if condition which is quite an overkill.

You may also like: Create your own custom Blade directive in Laravel

The unless condition

This PR, #30492, registers an additional @unlesscustom directive (a negative if condition) to deal with such kind of a situation.

So, using this, the previous example would simplified to the following.

@unlessenv('production')
    // The application is not in the production environment...
@endenv

This looks much cleaner than the previous approach. isn’t it?

You can start using this feature starting from Laravel version 6.x.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?