Blade: escaping text and allowing new lines
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Incorporating user-input text into your application can be challenging, particularly when you want to preserve new line characters while also ensuring proper HTML escaping. The question of how to achieve this using Laravel's Blade template engine is not only a common one but crucial for maintaining the integrity and functionality of your website. Let us dive deeper into the various options available to you.
Option 1: Combining nl2br() with Blade
The nl2br() function converts new line characters (\n) in a string into HTML line breaks (<br/>). Incorporating this function with the standard Blade markup can help you preserve new lines. Here's an example:
However, this approach still escapes HTML entities in your text, which may cause some problems. For instance, if the user-input text contains a literal <br/>, it will be replaced by its entity and no longer function as an actual HTML line break.
Option 2: Using Blade's Triple Brackets with nl2br()
Another way to escape the text while preserving new lines is using a combination of Blade's triple brackets and nl2br(). This method allows you to display your user-input text, keeping both functionality intact:
```php {{{ $text }}} ```However, the above syntax escapes any <br/> tags as well. Fortunately, we can use a slightly modified approach to maintain the HTML line breaks while still enabling proper escaping:
Option 3: Employing Blade's AutoEscaping
Laravel's Blade template engine comes with an optional auto-escaping feature. By default, it automatically escapes any HTML entities in your templates. If you wish to disable this functionality and allow new lines while preserving HTML entities, it can be accomplished using the following syntax:
```php @noEscaped {{ $text }} @endnoEscaped ```Conclusion
In summary, there are various ways to manage user-input text with new lines and proper HTML escaping in Laravel's Blade templates. Each option comes with its own advantages and drawbacks. While Option 1 is the most straightforward, it does not preserve HTML entities. Option 2 allows for better control, but requires more code. Option 3 provides a cleaner syntax at the expense of potentially unescaped HTML tags. Choose the one that aligns best with your application's security and functionality needs while still maintaining user input integrity.
Laravel Company, a leading software development agency, can help you build robust and secure applications using Laravel and Blade. Our team of experienced developers will ensure that your application remains highly functional and offers the best user experience possible.