首页 > 解决方案 > Laravel 通知 - 尝试从控制器传递数据

问题描述

HomeController.php我发送这样的通知$user->notify(new OutdatedAELocation($conSite));

然后在OutdatedAELocation.php我尝试使用这些数据将通知存储到数据库。

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class OutdatedAELocation extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($conSite)
    {
        $this->CSid = $conSite->id;
        $this->outdatedAes = $conSite->outdatedAes;
        $this->link = $conSite->link;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }


    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {   
        // dd($this);
        return [
            'conSite_id' => $this->CSid,
            'outdatedAes' => $this->outdatedAes,
            'link' => $this->link,
        ];
    }
}

由于某种原因,数据不会出现在toArray方法中。

当我dd($this)在 __construct() 方法的末尾调用时,它就在那里:

App\Notifications\OutdatedAELocation {#1329 ▼
  +id: null
  +locale: null
  +connection: null
  +queue: null
  +chainConnection: null
  +chainQueue: null
  +delay: null
  +middleware: []
  +chained: []
  +"CSid": 1
  +"outdatedAes": "info, "
  +"link": "https://app.com/query?location=1"
}

但是,当我在方法dd($this)的第一行调用时toArray(),它是这样的:

App\Notifications\OutdatedAELocation {#1780 ▼
  +id: "ac659b25-7ff2-4500-adc8-72e6508d50c6"
  +locale: null
  +connection: null
  +queue: null
  +chainConnection: null
  +chainQueue: null
  +delay: null
  +middleware: []
  +chained: []
}

请问,我怎样才能通过数据?

谢谢你。

标签: phplaravelnotifications

解决方案


首先,您必须定义类中的成员:

<?php

class OutdatedAELocation extends Notification implements ShouldQueue
{
    use Queueable;

    // HERE you define the members
    var $CSid;
    var $outdatedAes;
    var $link;

    // ...
}

之后尝试dd($conSite);在构造函数的开头查看是否将完整对象传递给类。


推荐阅读