【问题标题】:Laravel | Passing variable in Notify拉拉维尔 |在通知中传递变量
【发布时间】:2018-05-16 09:18:36
【问题描述】:

我想向 Notify 发送邮件,它可以工作,但是当我尝试放置变量时,它返回它们未定义。我不明白如何将变量传递给 Notify,我尝试过 ->withResult($result) 但没有成功。 这是控制器:

    $result = Review::where('user_hash', '=', $data['lname_c'])->where('email', $data['email_c'])->orderBy('created_at', 'desc')->first();
    $result->notify(new SendReview());

还有我的 SendReview.php 通知:

public function toMail($notifiable)
{

    return $result['invitation_id']; // test to check if variable is passed
    return (new MailMessage)
                ->line('Test.')
                ->action('Nani', url($url))
                ->line('Thank you');
}

我的 Review 表中有 user_hash 和invitation_id,我想将它们传递给通知。当我做return $result['invitation_id']; 时,它可以工作。希望我可以理解,我检查了重复的问题,但找不到。

【问题讨论】:

    标签: php laravel email notify


    【解决方案1】:

    这就是他们在文档中的做法。

    $arr = [ 'foo' => "bar" ];
    $result->notify(new SendReview($arr));
    

    在你的SendReview.php

    ...
    
    protected $arr;
    
    public function __construct(array $arr) {
            $this->arr = $arr;
    }
    
    public function toMail($notifiable) {
            // Access your array in here
            dd($this->arr);
    }
    

    【讨论】:

    • 当我做dd($notifiable['invitation_id'])它返回值但我不能做return $notifiable['invitation_id'],我该怎么做?
    • 为什么需要返回$notifiable['owner']?这对我来说根本没有意义。
    • $notifiable['invitation_id']* 抱歉
    • 您不必在 toMail() 方法中返回这些 ID
    • 您实际上可以通过访问 notifiable 参数在您的 toMail() 方法中构建 url。如果您需要在$result->notify(new SendReview()) 之后访问invitation_id,您可以使用$result->invitation_id 获得它
    【解决方案2】:

    您必须在 Notification 类中使用 $notifiable 变量。

    它是通知发送到的类的一个实例。所以这里你的评论对象作为$notifiable 变量传递。

    您可以尝试在toMail() 方法中将其记录为logger($notifiable) 并检查其属性。

    【讨论】:

      【解决方案3】:

      对于有兴趣传递对象(例如 $msg_recipient)并从控制器向特定用户发送电子邮件的人。

      控制器:

      记得加use Illuminate\Support\Facades\Notification;

       Notification::route('mail',$msg_recipient->email)
                              ->notify(new MsgReceived($msg_recipient));
      

      在您的通知中 __construct

      public function __construct($msg_recipient)
          {
              $this->username = $msg_recipient->username;
          }
      
      

      toMail 功能

      public function toMail($notifiable)
          {
              $username = $this->username;
      
              return (new MailMessage)
                          ->greeting('Hello, '.$username)
                          ->line('You received a brand new msg!')
                          ->action('View msg', url('/'.$username));
          }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-11
        • 2017-08-22
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多