Create Your Own Blade Directive: Example of br2nl in Laravel

Recently I had a task of textarea fields to save data with <br /> for new lines in database but not show them in the forms. There’s a PHP function called nl2br for conversion, but there’s no official opposite br2nl. Turns out, it’s a pretty simple replace method, but how to add it to Blade as a function? With that, I will show you an example how to create your own Blade directive.

First, here’s what we have in PHP language, found this “unofficial” method in the comment on the official website:

function br2nl($string)
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);

Ok, now – how do we use that in Blade when parsing textarea value? We need something like this:

<textarea>{{ br2nl($post->post_text) }}</textarea>

Of course, we can register that function as a helper, add it to PSR-4 in composer.json and just use it. But since it will be used only in Blade, I decided to create a Blade directive, so it would work like this:


To do that, we need to register the directive in app/Providers/AppServiceProvider.php in boot() method:

public function boot()
    Blade::directive('br2nl', function ($string) {
        return "<?php echo preg_replace('/\<br(\s*)?\/?\>/i', \"\n\", $string); ?>";

Notice, that we’re not returning just replaced string, we need to return the PHP syntax so it would echo the result.

Finally, to make sure it’s not cached somewhere, we need to run this:

php artisan view:clear

And that’s it! Nothing more to change in the code, it’s that simple to add your own Blade directives.

You may find some more information, in the official documentation – see section Extending Blade.

Like our articles?
Check out our Laravel online courses!


Please enter your comment!
Please enter your name here