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

sbkl's avatar
Level 17

Vuejs - How to return a string with line break from database

Hello,

The title is self-explanatory.

A user record a message as follow:

"Hello, This is my first message."

When I get the message, the JSON format get it as follow:

"Hello,\nThis is my first message"

And when I call the element to the DOM, we can see it on the page as follow:

"Hello, This is my first message."

I tried to use a get function in the Message Model with php nl2br on the message attribute before to send it to vue. However, I get the following: "Hello,< br />This is my first message."

How do we keep the line break from the initial message entered by the user? Can it be done in blade?

Thank you.

0 likes
5 replies
michaeldyrynda's avatar
Level 41

I'm not familiar with Vue specifically, but it sounds like you're adding text to your element. Is there some Vue method to populate the target element with html? Then you can pass the nl2br'd value to that.

For example, with vanilla javascript you can set the content of a target element using either target.innerText or target.innerHTML. The former would render the string "Hello,<br />This is my first message", the latter will render the proper HTML.

Edit: It looks like you may be able to use {{{ data }}} (rather than {{ data }}?) to render the HTML in your target element using Vue.

1 like
sbkl's avatar
Level 17

Thank you Deringer. Following your answer, I have found the v-html attribute with vuejs.

1- I have setup a getMessageAttribute in the Message model to return the message through the nl2br() php function which insert < br /> tags to identify the line breaks

2- In the blade page, I have inserted the vuejs attribute v-html: before: < p >@{{ message }}< /p > after: < p v-html="message">< /p >

And it works!

2 likes
reedmaniac's avatar

Beware that if you are outputting HTML and the message is user inputted, than any HTML they input will be rendered on the page.

CharlesCook's avatar

In 2024, for those wondering how to do this from a controller to a vue file:

    $time =nl2br("test this \n line");
     'time' => $time,
     <p  v-html="time" ></p>

Please or to participate in this conversation.