We are already familiar with some laravel blade directives like @auth @if @empty @guest @section and many more. But in this tutorial, we will see how to create custom blade directive in laravel. It is very easy to create custom blade directives laravel.

To create this custom blade directive in Laravel, we can use Blade::directive() method. I will share the source code of custom blade directive laravel. So let's see the way that how to create laravel blade directives:

laravel-custom-blade-directive

app\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('convert', function ($number) {
            return "<?php echo number_format($number, 2); ?>";
        });
    }
}

 

And now simply call it in your any blade file to convert the number with our own custom blade directive:

resources/views/any_file.blade.php

@convert($var)

 

Read also: How To Use Switch Statement In Laravel Blade

 

Conclusion

I have tried to discuss the clear concept of laravel blade directives. Now we know how to create custom blade directive in laravel. Hope this create custom blade directives laravel tutorial will help you.