DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Enhancing Blade with Custom Directives

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();
    });
}
Enter fullscreen mode Exit fullscreen mode

Then, you can easily use it like this:

@isGuest
    <p>You are a guest</p>
@endisGuest
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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

@isAuth

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

@endisAuth
Enter fullscreen mode Exit fullscreen mode

Top comments (0)