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.

 

#laravel #laravel-8x #custom #blade