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

如何在Laravel中使用Pusher实现数据删除的实时同步?

Laravel + Pusher 实现数据删除后实时更新页面

1. 安装并配置Pusher

先搞定Pusher的依赖和基础配置:

  • 安装Pusher PHP SDK:
    composer require pusher/pusher-php-server
    
  • 修改.env文件,设置广播驱动和Pusher参数:
    BROADCAST_DRIVER=pusher
    
    PUSHER_APP_ID=你的Pusher应用ID
    PUSHER_APP_KEY=你的Pusher应用Key
    PUSHER_APP_SECRET=你的Pusher应用Secret
    PUSHER_APP_CLUSTER=你的Pusher集群(比如ap1)
    
    # Laravel 9+ 需补充VITE前缀变量
    VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
    VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
    
  • 启用广播服务:打开app/Providers/BroadcastServiceProvider.php,取消注释Broadcast::routes();这一行(默认该服务提供者已在config/app.php中注册,无需额外操作)。

2. 创建广播事件

生成用于广播数据删除动作的事件类:

php artisan make:event DataDeleted

编辑app/Events/DataDeleted.php,实现ShouldBroadcast接口,定义广播频道和携带的数据:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\InteractsWithSockets;
use Illuminate\Queue\SerializesModels;

class DataDeleted implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $dataId;

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

    // 指定广播频道,这里用公共频道;若需用户隔离可替换为私有频道
    public function broadcastOn(): array
    {
        return [new Channel('data-updates')];
    }

    // 定义传递给前端的事件数据
    public function broadcastWith(): array
    {
        return ['id' => $this->dataId];
    }
}

3. 在删除逻辑中触发事件

假设你的数据模型是Fruit,在删除控制器方法中,完成数据删除后触发广播事件:

public function destroy(Fruit $fruit)
{
    $deletedId = $fruit->id;
    $fruit->delete();

    // 广播数据删除事件
    event(new \App\Events\DataDeleted($deletedId));

    return redirect()->back()->with('success', '数据已删除');
}

4. 前端配置与监听事件

(1)引入依赖JS

在数据展示页面的底部引入Pusher和Laravel Echo的JS:

<script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
<script src="{{ mix('js/app.js') }}"></script>

(2)配置Echo

打开resources/js/bootstrap.js,取消注释Echo相关代码,替换为你的Pusher配置:

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    forceTLS: true
});

修改后编译前端资源:

npm run dev

(3)监听事件并更新DOM

假设展示数据的HTML结构如下(每个项带唯一ID):

<ul id="fruit-list">
    @foreach($fruits as $fruit)
        <li id="fruit-{{ $fruit->id }}">{{ $loop->index + 1 }}. {{ $fruit->name }}</li>
    @endforeach
</ul>

在页面中加入JS代码,监听广播事件并移除对应DOM元素(可选重新排序序号):

// 监听data-updates频道的DataDeleted事件
window.Echo.channel('data-updates')
    .listen('DataDeleted', (event) => {
        const element = document.getElementById('fruit-' + event.id);
        if (element) {
            element.remove();
            // 可选:重新更新列表序号
            document.querySelectorAll('#fruit-list li').forEach((item, index) => {
                const name = item.textContent.split('. ')[1];
                item.textContent = `${index + 1}. ${name}`;
            });
        }
    });

5. 测试验证

  • 启动Laravel本地服务:php artisan serve
  • 若使用队列驱动(如database),需启动队列:php artisan queue:work(默认同步驱动可跳过,但生产环境建议用队列)
  • 同时打开数据展示页和删除页,删除一条数据,展示页会自动移除对应项,无需刷新。

内容的提问来源于stack exchange,提问作者ARMAN UMAR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:09:12