'How to insert a line break in a markdown Notification
I'm using Laravel's Notifications system to send a welcome email when users register. Everything works great, except I can't for the life of me figure out how to insert a line break in the greeting.
This is my code:
namespace App\Notifications\Auth;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class UserRegistered extends Notification
{
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome to website!')
->greeting('Welcome '. $notifiable->name .'!')
->line('## Sub heading line')
->line('Paragraph line')
->markdown('mail.welcome');
}
}
I want to put a break here ->greeting('Welcome '. $notifiable->name .'!') between the welcome and the name. Anyone know how I can do this? I've tried double space as described on markdown documentation. I've tried using nl2br(). I've tried \n. I've tried <br>. Nothing works.
Solution 1:[1]
First of all, make sure to render the string as HTML in your mail view:
{!! $greeting !!}
As mentioned in the answer above, this makes it possible to use <br> inside of ->greeting().
Nevertheless, it's better to use nl2br(). This renders \n as a new line in the HTML mail as well as in the plaintext mail. (Otherwise the <br> is not rendered in the plaintext mail!)
Note: nl2br() only works with a string in double quotes, not single quotes!
Use it in your notification like this:
public function toMail($notifiable)
{
$name = $notifiable->name;
return (new MailMessage)
->subject('Welcome to website!')
->greeting(nl2br("Welcome\n$name!"))
->markdown('mail.welcome');
}
Output as HTML:
<p>Welcome<br>
Username!</p>
Output as plaintext:
Welcome
Username!
Solution 2:[2]
Got it to work. Turns out is was in the markdown where the issue lay because of Laravel's escaping HTML when using {{ }}. You have to prevent escaping by using {!! !!}: Using double curly brace in Laravel Collective
For those interested my greeting line is now ->greeting('Welcome<br>'. $notifiable->name .'!')
and in my markdown template it's
{{-- Greeting --}}
@if (! empty($greeting))
# {!! $greeting !!}
@endif
Solution 3:[3]
You can just do following:
public function toMail($notifiable)
{
$name = $notifiable->name;
return (new MailMessage)
->subject('Welcome to website!')
->greeting(new HtmlString("Welcome<br>$name!"))
->markdown('mail.welcome');
}
This doesn't require to edit any templates.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | James |
| Solution 3 | Vedmant |
