DEV Community

Cover image for Laravel Custom Blade Directive
bilalthepunjabi
bilalthepunjabi

Posted on

Laravel Custom Blade Directive

Hi there folks,

Today, I would like to talk about the laravel custom blade directives. You would have probably seen @if, @endif which are called directives.

In this post, I would help you to create your own directives and their limitations and use-cases that will eventually help you to make your application developments much easier.

We will got through the example directive here. First create a provider with artisan.

php artisan make:provider BladeServiceProvider

The path will be app/Providers/BladeServiceProvider

<?php

namespace App\Providers;

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

class BladeServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Enter fullscreen mode Exit fullscreen mode

@print(object)

In the boot function of the provider we have just created.

Blade::directive('print', function ($payload) {
     return "<?php 
       echo'<pre>';
       print_r($payload);
       echo'</pre>'; 
     ?>";
});
Enter fullscreen mode Exit fullscreen mode

We can then use this directive as @print($any_object_or_array) in any blade template.
If this directive don't work or display then the issue lies with the cache. You have to purge the view cache or you can run php artisan optimize:clear to purge all cache of any type.

This is just minimal implementation and use-case of blade-directives.

Limitations & Issues

The main issue you will encounter with the results of this custom-directive is of cache. If you don't make these to be dynamic in-nature. Then laravel cache engine nullified your generic-behaviour of your directive.

Blade::directive('{name}', function () { return 'string_expression'})

{string_expression} is an expression in string form like
"<?php ehco('Hello World'); ?>".

But if you passed something un-proccessed form of code like using another directive or laravel blade-view injection like
return view('blade',compact($var));.
It conflict with the cache-engine of laravel.

If you want to render the some blade template on using your directive you can code something like
return "<?php echo view('blade',compact('$model'))->render(); ?>";.

If you have any query or problem that you wanna share then just ping @bilalthepunjabi in discussions.

Discussion (0)