1

I'm using Laravel 5.3 and I'm trying to send an email with nl2br(). So I'm using the default email blade file that's new in Laravel 5.3 (vendor/notifications/email.blade.php)

But it does not show line breaks. Only this:

sttesttesttesttesttesttesttesttesttesttesttesttest<br /> <br /> <br /> <br /> testtesttesttesttesttesttesttesttesttesttesttesttesttesttest

I've done it like this:

<!-- Outro -->
@foreach ($outroLines as $line)
    <p style="{{ $style['``'] }}">
        {{ nl2br($line) }}
    </p>
@endforeach

What am I doing wrong?

This:

{!! nl2br(htmlspecialchars($line)) !!}

is not working.

Jamie
  • 10,302
  • 32
  • 103
  • 186
  • 1
    Possible duplicate of [Laravel 5.3 nl2br in email](http://stackoverflow.com/questions/40220996/laravel-5-3-nl2br-in-email) – S.I. Nov 03 '16 at 12:25

3 Answers3

4

Laravel automatically escapes your string by using {{ }}

For laravel 4+ use {{{ nl2br($line) }}}

For laravel 5+ use {!! nl2br($line) !!}

Correct me if i'm wrong on the versioning.

2

For Laravel 4 users:

{{ nl2br(e($message)) }}

e($x) is equivalent to {{{ $x }}}.

Laravel 5 users:

{!! nl2br(e($message)) !!}

e($x) is equivalent to {{ $x }}.

S.I.
  • 3,250
  • 12
  • 48
  • 77
0

I know this is a bit late, but for everyone with the same problem. If you are using the notifications mail, new lines will not work ("\n", "\r", "\r\n").

This is because Laravel (for 5.3 and 5.4 I can confirm) strips these from the lines

vendor\laravel\framework\src\Illuminate\Notifications\Messages\SimpleMessage.php

protected function formatLine($line)
{
    if (is_array($line)) {
        return implode(' ', array_map('trim', $line));
    }

    return trim(implode(' ', array_map('trim', preg_split('/\\r\\n|\\r|\\n/', $line))));
}

How I solved this is by replacing the new lines with actual html new lines <br>.

There are much better ways of doing this I'm sure, but the important part is not to overlook the formatLine function.

public function toMail($notifiable) {

    //Get your mail data
    $mail = new Email(2);
    $emailLine = $mail->getArray();

    return (new MailMessage)
        ->line(str_replace(array("\\r\\n", "\\n", "\\r","\r\n", "\n", "\r"), "<br>", $emailLine))

}

Casper Spruit
  • 944
  • 1
  • 13
  • 31