如何在邮件通知laravel上添加条件?

时间:2017-12-10 19:01:14

标签: laravel email laravel-5 notifications laravel-5.3

我使用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)不显示或未执行

我该怎么做?

1 个答案:

答案 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;
}