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

Drewlim7's avatar

How to encode html text and display decoded html text correctly

May I know which is the best practice for encoding HTML texts and decode HTML texts when display content?

Should I handle it at the controller before to blade or handle it at the blade view? If I handle it at blade view, should I include e($text) to escape?

May I know which one Is the correct example below?

Example 1:

Controller.php

htmlspecialchars($text) //To encode and store into db
htmlspecialchars_decode($text) // to decode and display text to blade view

blade

<p> {!! nl2br($text) !!}</p>

Example 2:

Controller.php

htmlspecialchars($text) //To encode and store into db

blade

<p> {!! htmlspecialchars_decode(nl2br($text)) !!}</p>

Example 3:

Controller.php

htmlspecialchars($text) //To encode and store into db
htmlspecialchars_decode($text) // to decode and display text to blade view

blade

<p> {!! htmlspecialchars_decode(nl2br(e($text))) !!}</p>

Example 4:

Controller.php

htmlspecialchars($text) //To encode and store into db

blade

<p> {!! htmlspecialchars_decode(nl2br($text)) !!}</p>
0 likes
4 replies
Tray2's avatar

As a rule of thumb, never ever use {!! $variable !!} unless you really can trusts the source and actually avoid it even if you can.

I'm guessing this is a blog or somewhere you allow tha user to input html into the database.

I would go with Markdown instead of html so I wouldn't have to worry as much about the user breaking the page.

Laravel by default escapes html before storing it in the table.

Drewlim7's avatar

@tray2 Actually I am allowing the user to input their description in a textarea tag and this is where I store the $text to database. However, what if I insist to go with textarea and not using markdown, what is the best solution to solve in my case?

Drewlim7's avatar

@jlrdw Do you have any experience in solving my problem? Which example should I go for?

Please or to participate in this conversation.