How to create custom blade directive in laravel ?

In this article, We’ll see how we can create a custom blade directive in laravel.

Blade allows you to define your own custom directives using the directive method.

In laravel’s documentation, a new blade directive creates under boot method in AppServiceProvider.php, but we’ll create a new provider, so lets create it using artisan command.

  php artisan make:provider BladeServiceProvider

add your new service provider in the /config/app.php file in the providers array:

 App\Providers\BladeServiceProvider::class




add blade facade at the top of the file in BladeServiceProvider.php

  use Illuminate\Support\Facades\Blade;

create your custom directive under boot method in code>BladeServiceProvider.php, for ex:

  Blade::directive('message', function ($expression) {
      return 'Hello ' . $expression;
  });

We’ll need to delete all of the cached Blade views using the next Artisan command:

  php artisan view:clear

This directive will display the “Hello World !” message. So now you can use it in any Blade file:

  @message(World !)
  // Hello World !

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *