Properly display line breaks from a <textarea> using Blade

If you have a <textarea name="content"> field in your form and you use {{ $post->content }} in your Blade template to display the $post->content field, you’ll notice that none of the line breaks are retained when the field is rendered on the page.

For example, text entered into a <textarea> like this:

The plants and flowers
I raised about my hut
I now surrender
To the will
Of the wind

Will be displayed on your page like this:

The plants and flowersI raised about my hutI now surrenderTo the willOf the wind

That does not do the Ryokan poem justice.

To fix our line break issue, replace {{ $post->content }} with {!! nl2br(e($post->content)) !!}

Let’s break that down working from the most inner function out to the wrapping Blade statements.

We first wrap $post->content with the escape function e(). The Laravel e() function runs PHP’s htmlspecialchars function with the double_encode option set to false. Laravel Documentation

Next we have nl2br() which inserts HTML line breaks (ie. <br> tags) before all newlines in a string. PHP Documentation

Lastly, we change our Blade statement from {{ ... }} to {!! ... !!} which disables the escaping of data between the curly braces. But we’ve already escaped the data using the e() function.

Important – If you choose to prevent escaping by using the {!! ... !!} statement, be sure to escape your data before rendering it on the page… or else.

Now your line breaks are retained.

Leave a Reply

Your email address will not be published. Required fields are marked *