Laravel: Registering your Blade directives the cool way

Also known as “stop doing it the wrong way”

Italo Baeza Cabrera
2 min readJun 1, 2020
Photo by Ali Kazal on Unsplash

Custom Blade directives in Laravel are very handy to allow some quick logic around an “expression” without having to pollute our views with verbose code, and allows to have them reachable in any view.

The problem of these is that registering them has been always a pain in the ass. What a directive must return is a string of inert PHP code but with a live the expression variable. The Laravel documentation points this is the way:

Blade::directive('datetime', function ($expression) {
return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
});

This can become very cumbersome when you need to make logic that is more than just one line. Most IDE and Code Editors don’t help when you are using this kind of code, so we can’t optimally get code assistance when using this kind of strings.

Alternatively, we can register a directive by just reading a PHP file. That’s it. Yep. You heard that right.

The cool way

We can create a directive in a PHP file anywhere and then retrieve its contents from the function itself. For that, we can use the File facade.

Blade::directive('datetime', function ($expression) {
$contents = File::get(__DIR__ . '\datetime_directive.php');
$replaced = str_replace('$expression', $expression, $contents); return Str::finish($replaced, '?>');
});

Since we’re retrieving the PHP file as a string, the expression variable will become a string unless we replace it with the expression value itself. After that, we will ensure the contents finish with a PHP closing tag.

And what contains our directive? Well, it’s just plain PHP code:

<?phpecho ($expression)->format('m/d/Y H:i');

This will allow to use this directive in our Blade views easily:

This post was published at @datetime($post->published_at).

The above will be compiled to

This post was published at <?phpreturn ($post->published_at)->format('m/d/Y H:i'); ?>.

and will be rendered as:

This post was published at 01/01/2020 22:30.

This code is available in my Laratraits package for Laravel, with a lot of other useful tools. Check it out if you don’t want to reinvent the wheel.

--

--

Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com