在 Laravel 5.4 中使用通知

Using Notifications in Laravel 5.4

我一直在尝试在我的应用程序中实现通知,方法是将它们存储在数据库中,详见此处的文档:https://laravel.com/docs/5.5/notifications

这是我的卡车模型,具有引用的应通知特征

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Notifications\Notifiable;

use App\Driver;

class Truck extends Model
{
    use Notifiable;
}

这里是通知class我用nameddue_for_maint

<?php

namespace App\Notifications;

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

class due_for_maint extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
          'truck_no' => $this->truck->registrationNo,
          'Milage' => $this->truck->readingMilage,
        ];
    }
}

这是我卡车控制器中的一个函数,称为 notifi_me 方法,我用它来创建通知

public function notifi_me(){
$truck = Truck::find(10);
$truck->notify(new due_for_maint($truck));



}

每当我调用 notifi_me 函数时,我都会收到此错误:

Undefined property: App\Notifications\due_for_maint::$truck

有人可以解释为什么会这样吗?我该如何解决? 我的理解是 Laravel 在 Truck 对象和通知之间建立了一种关系,这应该使卡车属性在通知 class.[=16 中使用类似 $this->truck->id 的语法来引用=]

只需将缺少的 属性 添加到您的通知中 class :

private $truck;

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

toMail 和 toArray 函数中的可通知参数是卡车本身,因为这就是您所说的通知对象。您不必在构造函数中执行任何操作,只需替换

return [
    'truck_no' => $this->truck->registrationNo,
    'Milage' => $this->truck->readingMilage,
];

return [
    'truck_no' => $notifiable->registrationNo,
    'Milage' => $notifiable->readingMilage,
];

一切顺利!