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)

 

Read also : Avoid json_encode() and Use @json() Blade Directive

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.