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

Amit Merchant

A blog on PHP, JavaScript, and more

Creating your own custom conditional directives in Laravel Blade

Laravel’s Blade template engine is great and ever-evolving. There are some features in Blade, which if used appropriately, can make your codebase look more organized and recognizable.

One such feature that I recently came across is where one can create their own custom conditional Blade directives which you can use in your codebase. This kind of Blade directives can come in handy if you don’t want to spoil your Blade views by throwing in the complex logic and to make your views much cleaner.

You can create a custom conditional directive using Blade::if method which you can define in the boot method of the AppServiceProvider.

So, if you want to create a custom conditional directive which checks the type of book and returns the boolean result accordingly, you can do it like so.

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    // code commented for brevity

    public function boot()
    {
        Blade::if('booktype', function ($booktype) {
            if (in_array($booktype, ['fiction', 'nonfiction'])) {
                return true;
            } 

            return false;
        });
    }
}

As you can see, the Blade::if takes two arguments. The first is the name of the custom conditional which we’re going to use in the Blade template. In our case, it’s booktype. And the second argument is the closure which performs the logic. This is, ofcourse, a really simple logic that I’ve defined but this can be useful when you want to put some more complex logic in place.

Once created, you can now use this custom conditional like so.

@booktype('fiction')
    // This is a fiction book
@elsebooktype('nonfiction')
    // This is a non-fiction book
@else
    // This book falls into some other category
@endbooktype

You can even use unless on the conditional just like the regular if directive if you only want to check for the specific booktype like so.

@unlessbooktype('nonfiction')
    // This is a non-fiction book
@endbooktype
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?