Laravel: Registering your Blade directives the cool way

Also known as “stop doing it the wrong way”

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

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, '?>');
});
<?phpecho ($expression)->format('m/d/Y H:i');
This post was published at @datetime($post->published_at).
This post was published at <?phpreturn ($post->published_at)->format('m/d/Y H:i'); ?>.
This post was published at 01/01/2020 22:30.

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.