in Laravel

How To Create A Custom Blade Directive

Blade is a PHP templating framework to use with your Laravel application. The blade templates are compiled down to normal PHP code. We can also extend blade by creating our own custom functions and directives to make our templates easier to handle.

Blade already comes with a load of it's own directives which can be found in laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php. These allow you to use shortcuts for things like htmlentities by using @e() or outputting JSON by using @json.

If you're doing the same logic multiple times in your blade templates you should look at creating your blade directives.

To create your own blade directive you can use the following code.

\Blade::directive('directive_name', function ($value) {
    return $value;
});

This will go in the AppServiceProvider inside the boot method. The return of the closure function will be what is complied into the template.

For example let's create a new directive that will show the full name of a user combining the firstName and lastName property.

\Blade::directive('fullname', function() {
    if (\Auth::check()) {
        $user = \Auth::user();
        return "{$user->firstName} {$user->lastName}";
    }
});

You can use this within the blade by doing

@fullname

That's all the code you need to help clean up your blade templates and create your own blade directives.

View Cache

One thing to remember is that Laravel will cache your view files with the compiled code from your custom blade directives. Therefore if you change your blade directive you will need to clear view cache by running php artisan view:clear.

Subscribe To The Weekly Newsletter

Get weekly updates to your email