How to create custom laravel blade directives?

10-Apr-2023

.

Admin

Hello Friends,

If you have to create custom directives like @yield then here is example. sometimes we are use same code multiple times then you have to create directives. then don't write same code.

Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

App\Providers\AppServiceProvider.php


namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider

{

/**

* Register any application services.

*

* @return void

*/

public function register()

{

//

}

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Blade::directive('datetime', function ($expression) {

return \Carbon\Carbon::today();

});

}

}

How to Use Custom Directive

<div>

@datetime

</div>

I hope it can help you...

#Laravel