【问题标题】:Conditional broadcastWith in Laravel Event?Laravel 事件中的条件广播?
【发布时间】:2021-01-19 11:07:46
【问题描述】:

我有一个会在多个渠道上发送信息的事件:

  • members 的频道
  • managers 的频道

这是我写的:

<?php

class ModelUpdated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $model;

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

    public function broadcastWith($who)
    {
        if ($who == "model.{$this->model->id}")
            return [$this->model->id];
        else if ($who == "model.{$this->model->id}.managers")
            return [$this->model];
        else 
            return [];
    }

    public function broadcastOn()
    {
        return [
            new PrivateChannel("model.{$this->model->id}"),
            new PrivateChannel("model.{$this->model->id}.managers")
        ];
    }
}

不幸的是,broadcastWith 不适用于我的 $who 魔法。有其他方法吗?

我想避免出现不同的事件,因为我的事件是在模型中触发的:

class MyModel extends Model
{
    use Notifiable;
    
    protected $dispatchesEvents = [
        'saved' => ModelUpdated::class,
        'updated' => ModelUpdated::class,
    ];
}

【问题讨论】:

  • 代码中的模型是什么?
  • 一个雄辩的模型

标签: php laravel broadcast


【解决方案1】:

据我所知broadcastWithdoes not accept any parameter,Laravel 8.x。 您需要通过构造函数传递所有数据,然后决定您需要返回什么作为事件的有效负载。

确保从broadcastWith() 方法return an array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2017-05-04
    • 1970-01-01
    • 2023-03-04
    • 2020-07-28
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多