问题
I use laravel 5.3
My notication laravel like this :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\BroadcastMessage;
class GuestRegistered extends Notification implements ShouldBroadcast, ShouldQueue
{
use Queueable;
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('test')
->greeting('Hi')
->line('Thanks')
->line('Your password : '.$this->data)
->action('Start Shopping', url('/'));
}
}
I want to add condition in toMail method
So if $this->data
not exist then ->line('Your password : '.$this->data)
not display or not executed
How can I do it?
回答1:
You can store the MailMessage
instance as a variable, use an if
statement and then return it.
public function toMail($notifiable)
{
$mailMessage = new MailMessage();
$mailMessage
->subject('test')
->greetings('Hi')
->line('Thanks');
if($this->data) {
$mailMessage->line('Your password: ' . $this->data);
}
$mailMessage->action('Start Shopping', url('/'));
return $mailMessage;
}
Don't forget adding a default value for the $data
parameter.
public function __construct($data = null)
{
$this->data = $data;
}
来源:https://stackoverflow.com/questions/47742370/how-can-i-add-condition-on-mail-notification-laravel