ENHANCING BLADE WITH CUSTOM DIRECTIVES

Jun 23, 2025 Copy Link

If you're using the same condition repeatedly in Blade, especially if it's complex, you likely won't want to repeat it multiple times. To avoid this, Laravel provides a neat way to define your condition once in the AppServiceProvider class:

 

use Illuminate\Support\Facades\Blade;

/**
* Bootstrap any application services.
*/
public function boot(): void
{
    Blade::if('isGuest', function () {
        return auth()->guest();
    });
}

 

Then, you can easily use it like this:

 

@isGuest
    <p>You are a guest</p>
@endisGuest

 

In addition, you can define a custom Blade directive like this:

 

/**
* Bootstrap any application services.
*/
public function boot(): void
{
    Blade::if('isAuth', function () {
        return auth()->check();
    });

    Blade::directive('welcomeUser', fn($name) => "Welcome $name");
}

 

Once defined, you can use these custom directives in your Blade templates like this:

 

@isAuth

@welcomeUser(auth()->user()->name)

@endisAuth

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE