DEV Community

Cover image for Laravel 8 - Custom nl2br Blade Directive
Zack Webster
Zack Webster

Posted on

Laravel 8 - Custom nl2br Blade Directive

Wouldn't it be cool if Laravel came with a few helper directives like nl2br? Well, hopefully, they will include it in the future. For now, I am going to show you how to set up a custom one yourself.

The Setup

First, open up your AppServiceProvider.php file from app/Providers.

Here we define, our blade directive in the boot() function as follows:

<?php

namespace App\Providers;

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

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Blade::directive('nl2br', function ($string) {
            return "<?php echo nl2br(htmlentities($string)); ?>";
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

The Usage

You can now use our custom-built @nl2br() directive in any our your Blade views.
An example:

<div class="description">
    @nl2br($description)
</div>
Enter fullscreen mode Exit fullscreen mode

That's All

Great, now you know just a bit more about the Laravel world. If you come up with more such directives I'd love to see them in the comments.

Thanks for reading.

Discussion (0)