Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

begimov's avatar

Safe way to keep line breaks

Users insert some text into mysql using wrapped in

 tags.

To preserve saved line breaks in blade template i use: {{!! nl2br(...saved text...) !!}}.

Is this a safe way of doing it?

Laravel docs: "Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data."

If it's not, is there another way?

Thank you!

0 likes
4 replies
jbloomstrom's avatar

Looks like the parser may have gotten confused. I'm not sure what kind of tags the text is wrapped in, but if all you want to do is preserve line breaks in the displayed html, you can wrap the output in <pre></pre> tags.

Pre means preformatted and will preserve line breaks.

...
<pre>{{ $saved_text }}</pre>
...

This is a safer approach, because it will still pass everything through the htmlspecialchars function to prevent XSS attacks.

You can also throw it into a <textarea></textarea>

...
<textarea readonly>{{ $saved_text }}</textarea>
...
3 likes
edoc's avatar
edoc
Best Answer
Level 24

What you need is {!! nl2br(e($text))!!}.

Use e Laravel helper function to purify your html before showing line breaks

@begimov

19 likes
kavickers's avatar

@edoc Incase anyone in the future comes across this answer... this is NOT safe to use on a modern web application, and can be exploited with a basic XSS attack.

Please or to participate in this conversation.