Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respect line breaks in Laravel blade

It is a doubt that I have tried to solve on my own using different methods, but none has given me the expected result.

The problem comes when I save a variable of type text in the database of my project. It saves it with line breaks, in fact when I try to edit it from one of my views, it respects those jumps. The problem comes when I want to show it in a blade.php view, where all the text is without any line break.

I have used different functions such as nl2br () or str_replace, and all they do is change the / n to the br tag for line breaks, and instead of applying those line breaks, write them on the screen next to the text.

I do not know if this change or modification to the variable should perhaps be executed on the server and sent to the view, instead of executing in the view {{nl2br ($ user-> proffile)}} or with str_replace.

First forgiveness for English and thanks in advance for the help

like image 396
FranRP Avatar asked Feb 01 '26 00:02

FranRP


2 Answers

You can do the escaping first, using e() and then apply nl2br():

{{ nl2br(e($user->proffile)) }}

e() is the function Blade uses when compiling triple brackets

For Laravel 5, use this: {!! nl2br(e($user->proffile)) !!}

like image 120
Hassaan Avatar answered Feb 02 '26 13:02

Hassaan


An even better approach is to use plain css for this:

<p style="white-space: pre-wrap">{{ $text }}</p>

Displaying unescaped text using {!! ... !!} is very dangerous because it allows XSS attacks.

like image 28
Alexander Braekevelt Avatar answered Feb 02 '26 13:02

Alexander Braekevelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!