首页 > 解决方案 > 如何使用 laravel 中的电子邮件通知使发件人的地址动态化

问题描述

我有一个关于 laravel 5.5 的项目,我的电子邮件通知工作正常,但我希望从数据库中选择发件人地址,而不是从通知中手动编码。

public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->from('hr@example.com', 'Example')
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

我的邮件陷阱邮件

截图

标签: phplaravel

解决方案


当您在 $user 对象上或通过外观调用 notify() 函数时,您可以通过(动态)地址

use App\Notifications\DemoNotification;
use Illuminate\Support\Facades\Notification;

class SomeController extends Controller
{
    public function demo()
    {
        //$data = Some model object or anything
        //$fromAddress = Pick from database 

        Notification::send($users, new DemoNotification($data,$fromAddress));

        //Or $user = auth()->user();

        $user->notify(new DemoNotification($data,$fromAddress));
    }
}

接受 DemoNotification 类的构造函数中的 fromAddress

class DemoNotification extends Notification
{

    use Queable;

    public $fromAddress;

    public $data;

    public function __construct($data, $fromAddress)
    {
        $this->data = $data;
        $this->fromAddress = $fromAddress;
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from($this->fromAddress, 'Example')
            ->line('The introduction to the notification.')
            ->action('Notification Action', url('/'))
            ->line('Thank you for using our application!');
    }
}

推荐阅读