You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Livewire实现类似Facebook铃铛图标的跨用户实时通知?

跨用户实时通知实现方案:Livewire + Laravel广播

仅靠基础Livewire无法实现跨用户的实时通知,因为Livewire默认的组件事件监听只作用于当前用户的会话连接。但你不需要额外引入第三方推送服务,通过Laravel广播系统配合Livewire就能解决这个问题。

为什么当前仅自己操作时能实时更新?

当你给自己分享Lead时,LeadCompartilhado事件触发后,当前页面的Notifications组件属于同一个用户会话,Livewire会自动同步组件状态。但其他用户的组件会话和你的完全隔离,无法感知到服务器端触发的事件,必须刷新页面拉取新数据。

实现跨用户实时通知的步骤

1. 配置Laravel广播系统

Laravel支持多种广播驱动,比如免费的Redis(需自行部署Redis服务),或者Pusher(有免费额度)。选择合适的驱动后,在.env里配置:

BROADCAST_DRIVER=redis
# 或者 BROADCAST_DRIVER=pusher

同时确保config/app.php中App\Providers\BroadcastServiceProvider::class未被注释,启用广播服务。

2. 修改事件类支持广播

让LeadCompartilhado事件实现ShouldBroadcast接口,并指定广播到目标用户的私有频道:

namespace App\Events;

use App\Models\Lead;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class LeadCompartilhado implements ShouldBroadcast
{
    use SerializesModels;

    public function __construct(public Lead $lead, public int $targetUserId)
    {
    }

    // 指定广播到目标用户的私有频道
    public function broadcastOn()
    {
        return new Channel('user.'.$this->targetUserId);
    }
}

3. 在Notifications组件中监听广播事件

在你的Livewire Notifications组件里,通过Laravel Echo监听目标频道的广播事件,触发组件数据更新:

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Laravel\Echo\Facades\Echo;

class Notifications extends Component
{
    public $unreadNotifications;

    public function mount()
    {
        $this->loadUnreadNotifications();
        // 监听当前用户的私有频道
        Echo::channel('user.'.Auth::id())
            ->listen('LeadCompartilhado', function ($event) {
                $this->loadUnreadNotifications();
            });
    }

    protected function loadUnreadNotifications()
    {
        $this->unreadNotifications = Auth::user()->unreadNotifications->take(5);
    }

    public function render()
    {
        return view('livewire.notifications');
    }
}

替代方案:轮询(非实时,但无需广播配置)

如果暂时不想配置广播系统,可以用Livewire的wire:poll指令定期刷新组件,但这不是真正的实时通知,只是间隔拉取数据:

<div wire:poll.5s>
    <!-- 未读通知列表 -->
    @foreach($unreadNotifications as $notification)
        <div>{{ $notification->data['message'] }}</div>
    @endforeach
</div>

轮询的缺点是有延迟,且会增加服务器请求量,适合低频次更新的场景。

总结

  • 不需要第三方推送服务,用Laravel广播+Livewire就能实现跨用户实时通知;
  • 广播方案是真正的实时更新,轮询是折中方案;
  • 私有频道确保只有目标用户能收到对应的通知事件。

内容的提问来源于stack exchange,提问作者Marcello Pato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:52:51