如何用广播解决laravel通知? Laravel 5.3

时间:2017-03-29 04:53:02

标签: php laravel notifications laravel-5.3 broadcast

我的控制器是这样的:

public function add($param)
{
    ...
    $message = Message::create([
        ...
        'created_at'            => Carbon::now(),
        'updated_at'            => Carbon::now()
    ]);
    Notification::send($notify_to, new MessageInsert($message));
    dd($message);
    return $message;
}

我的MessageInsert是这样的:

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MessageInsert extends Notification implements ShouldBroadcast, ShouldQueue
{
    use Queueable;
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function via($notifiable)
    {
        return ['broadcast','database','mail'];
    }
    public function toArray($notifiable)
    {
        return [
            'id'        => $this->data->id,
            ...
        ];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('Hello!')
            ->line('...')
            ->action('...')
            ->line('Thank you!');
    } 
}

如果是这样的话:

  

返回[&#39;广播&#39;,&#39;数据库&#39;,&#39; mail&#39;];

dd($message);的结果是错误

但如果是这样的话:

  

返回[&#39;数据库&#39;,&#39; mail&#39;];

dd($message);的结果是$message

的数组

使用广播时为什么会出错?

1 个答案:

答案 0 :(得分:2)

您是否尝试添加toBroadcast功能?

public function toBroadcast($notifiable) {
return new BroadcastMessage([ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]);
}