Extend Blade

Laravel allows you to extend blade by adding new directives and as of Laravel 5.1 it's really easy to do it.

In order to extend Blade we are going to need a Service Provider or we can use an already existing one. In this example I'm going to create a new one, because you might need it.

Service Providers are classes that are run before each requests and can be used for a lot of useful things, like passing data to all views.

Extend Blade by adding a new directive

The first thing we start with is creating the new Service Provider. So we will create a new file called BladeServiceProvider.php in app/Providers.

Now we have to register the new service provider. This can be done in the app/config/app.php file. You just have to add the new Service Provider class to the providers list. In our case, the new line should be App\Providers\BladeServiceProvider::class.

Service Providers have two methods, boot and register and we're going to need the former.

For this example I will create a new directive to check if the user is logged in and use it to display something only to authenticated users.

We will actually need to create two directives, similar to @if and @endif.

You should pay attention to some stuff, like including Blade with use Blade. Also when declaring a new directive you have to skip the @. The rest is pretty simple, as it's just basic php code wrapped in.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Blade;

class BladeServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('isuser', function() {
            return "<?php if(auth()->check()) : ?>";
        });

        Blade::directive('endisuser', function() {
            return "<?php endif; ?>";
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

You can even pass variables in the directive and it will look like this:

Blade::directive('hasrole', function($expression) {
	return "<?php if(auth()->check()->role($expression)) : ?>";
});

Blade::directive('endhasrole', function() {
	return "<?php endif; ?>";
});

There's a lot of stuff you can innovate with Blade directives and I would to hear about your experiences with them and what cool directives you've created.