我使用laravel 5.3
我的通知就像这样:
<?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('/'));
}
}
我想在toMail方法中添加条件
因此,如果$this->data
不存在,则->line('Your password : '.$this->data)
不显示或未执行
我该怎么做?
答案 0 :(得分:4)
您可以将MailMessage
实例存储为变量,使用if
语句然后将其返回。
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;
}
不要忘记为$data
参数添加默认值。
public function __construct($data = null)
{
$this->data = $data;
}