DEV Community

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

Posted on

4 1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay