Laravel 通过方法更改通知未进入 toMail 方法

问题描述 投票:0回答:1

我有一个类,我在 via 方法中计算变量,并且我想在

toMail
方法中使用相同的变量,但它在
toMail
方法中始终为空。知道为什么吗?

class FinancialQuestionnaireSubmissionNotification extends Notification implements ShouldQueue
{
    use Queueable,SerializesModels, GlobalMailHelperTrait;

    public Lead $lead;
    public $code;

    public function __construct(Lead $lead)
    {
        $this->lead = $lead->fresh();         
                          
    }
    public function via($notifiable)
    {

        $this->code = 'xyz';            
       
        return ['mail'];
    }
    /**
     * Get the mail representation of the notification.
     */
    public function toMail($notifiable)
    {                    
        dd($this->code);
    }   

    /**
     * Get the array representation of the notification.
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

这里我的

$this->code
始终为空,为什么即使在via方法中设置该变量之后!

laravel laravel-5 eloquent
1个回答
0
投票

我认为您正在使用 ShouldQueue 接口,它在被推入队列之前已被序列化。

因此代码将为空,因为当作业被推送到队列中时,$code 属性设置为“xyz”。但是,当实际处理作业并调用 toMail 方法时,它是该类的单独实例,并且 code 属性重置为其初始值。

你能做的一件事是,

public function __construct(Lead $lead)
{
    // other code
    $this->code = 'xyz';         
}

public function via($notifiable)
{
    return ['mail'];
}

现在,当作业被推送到队列时,$code 属性将被正确设置,并且当执行 toMail 方法时它将保留其值。

© www.soinside.com 2019 - 2024. All rights reserved.