Properly display line breaks from a <textarea> using Blade
If you have a <textarea>
field in your form and you use {{ $post->content }}
in your Blade template to display the post's content, 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 <textarea>
like this:
The plants and flowersI raised about my hutI now surrenderTo the willOf the wind
That does not do the Ryokan poem justice.
The fix
Replace this: {{ $post->content }}
With this: {!! nl2br(e($post->content)) !!}
What's going on here
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.
One gotcha
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.
Last updated on April 2021