Laravel 5.8按需通知错误在null上调用成员函数create()

时间:2019-03-11 18:44:01

标签: laravel laravel-5

当我这样做时,用户会收到没有错误的电子邮件:

Notification::send($user, new TicketNotification($details));

但是,当我这样做时,用户也会收到一封电子邮件,但以下屏幕截图中有错误

Notification::route('mail', 'email_of_non-db_user')->notify(new TicketNotification($details));

Error: Call to a member function create() on null

你知道为什么吗?如何避免此错误?

我必须使用“按需通知”,因为我需要向未存储为“用户”的人发送通知。

3 个答案:

答案 0 :(得分:0)

我想试试这个

TicketNotification更新via方法中,仅用于发送到邮件。

但是您也将通知保存到了数据库中。

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

答案 1 :(得分:0)

感谢Jignesh,您的回答有效。

对不起Thamer,我应该从一开始就发布整个代码。

之前是:

return ['mail','database']; 

仅现在:

return ['mail'];  

然后,不再有错误。

出现错误的我的TicketNotification:

<?php
namespace App\Notifications;

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

class TicketNotification extends Notification
{
    use Queueable;

    private $details;

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

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject($this->details['subject'])
                    ->greeting($this->details['title'])
                    ->line($this->details['body'])
                    ->line($this->details['links'])
                    ;
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'order_id' => $this->details['order_id']
        ];
    }
}

答案 2 :(得分:0)

将此添加到您的via方法中,以对所有问题使用相同的通知:

class_mode='multi_output'

您现在可以使用按需通知或向用户发送通知,而不必为每个频道或按需等发出多个通知。