2

I am developing a web application in PHP using the Laravel framework. One of the tables in my database is an 'Articles' table which has a content field. A user of the website enters text into a text area and this is inserted into a database using the following Laravel code:

$article = new Article;
$article->content = $request->content;
....other fields
$article->save();

This works fine. The article is inserted into the database and I can view it. Everything is grand. However, when the article is entered into the database, it does not recognise whitespace (i.e. I can't insert seperate paragraphs, it just joins them all together and displays them as one long paragraph).

I am aware of the nl2br function. Am I suppose to use nl2br BEFORE I save the Article to the database or am I only supposed to use it when outputting. I have followed the documentation that is available but it hasn't worked for me. Are there any other solutions?

Thanks for your help.


SOLVED

It was Laravel itself I think that caused a bit of problems with nl2br function. To display it correctly in a Laravel Blade PHP page is like so

{!! nl2br(e($article->content)) !!}

Thanks for your help guys.

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
Alex Naughton
  • 165
  • 3
  • 11
  • 2
    How are you viewing the database contents? I'd recommend only transforming data when outputting – Phil Jan 02 '17 at 23:59
  • 1
    What happens if you wrap the output in a `
    ` tag? I'd bet money your white space is preserved just fine.
    – Jordan Running Jan 03 '17 at 00:02
  • 1
    You should be able to call `nl2br` either _before_ you save the article into the DB (which means, you do it once and forget), or you can save the newline to the database and the call `nl2br` _every time_ you output the data. Both strategies can do the job. Which one to use depends mostly on whether you will _also_ use the data for other purposes other than displaying it, and what is more convenient in this case. – joanolo Jan 03 '17 at 00:04
  • I tried to add the
     and it didn't work. It inserted another text field into my Bootstrap text field and the text was centered.
    – Alex Naughton Jan 03 '17 at 00:12
  • 1
    someone should make an answer for this question. – lewis4u Jan 03 '17 at 09:04

0 Answers0