Enhancing Blade with Custom Directives
Mahmoud Ramadan

Mahmoud Ramadan @mmramadan496

About: Computer Science Geek 🧐 || Software Engineer 👨‍💻 || Digging Code Creator 🚀

Location:
Mansoura, Dakahlia, Egypt
Joined:
Jan 15, 2024

Enhancing Blade with Custom Directives

Publish Date: Jul 2 '25
0 0

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

Comments 0 total

    Add comment