Create custom blade directive in Laravel

Laravel uses a blade templating engine to render views and perform view-level operations using it. The Blade has some in-built directives that help to perform specific operations like checking conditions or handling loop operations. So you don’t need to repeat logic for that particular task.

In this tutorial, we will create a custom blade directive and take an example of that. With custom blade directives, we can clean up blade views and reuse the same logic.

The blade directive will compile and convert blade logic into PHP and HTML code and hide complex logic in the background. You will be familiar with blade directives like @if, @foreach, @section, or @yield. Let’s create a new blade directive as per our requirement.

Defining a Custom Blade Directive

To create a blade directive, we will use the Blade facade and its directive method. We need to define it into our boot method of AppServiceProvider so it will load automatically while the framework boots.

Below is the syntax to define blade directive:

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

Let’s create a welcome blade directive that will take the name as input and return a welcome message. To create open App\Providers\AppServiceProvider.php and modify as below:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Blade::directive('welcome', function ($name) {
            return "<?php echo 'Welcome '.{$name}; ?>";
        });
    }
}

Here, we have created a welcome directive that takes one parameter and returns a welcome message with that parameter. Now we can use it in a blade file like this:

@welcome('John')

// Or

@welcome('Wick')

Conclusion

In this article, we have created a simple blade directive that will print a welcome message. Here, you can apply any logic to this blade directive.