How to Create Custom Blade Directive in Laravel

Hey artisan in this tutorial i will show you how you can create your own custom blade directive. Laravel Blade comes with many in-built directives such as @section@yield@parent@json and several others, all of which have a certain purpose attached to them.

For instance, the @json directive can be used to encode JSON instead of directly using json_encode like so. Laravel gives us the ability to define our own custom directives using the directive method on the Illuminate\Support\Facades\Blade facade. 

For, instance, if you want to create a custom directive called @convert($var) to convert the provided number to two decimal places, you can define that into the AppServiceProvider’s boot method like so.

app\Providers\AppServiceProvider.php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    // code commented for brevity

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

 

Now simply call it like so

@convert($var)

 

Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js