php artisna make:event MessagePosted
db message 保存成功后,使用event(new EventClass())
app_id = "269039" key = "" secret = "" cluster = "mt1"
取消 App\Providers\BroadcastServiceProvider::class, 的注释
文档 ##!! 注意laravel5.4,要在config/app.php添加一条aliase: 'Pusher' => Pusher\Pusher::class, 否则系统找不到Pusher !!
安装需要的一些前后端 package
composer require pusher/pusher-php-server
打开 /resources/assets/js/bootstrap.js 取消以下内容注释,激活echo js组件
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: "pusher",
key: "",
cluster: "mt1",
encrypted: false
});
(Laravel Echo 是一个 JavaScript 库,可以订阅频道和监听由 Laravel 广播的事件)
npm install --save laravel-echo pusher-js
在页面js中的代码: (使用private频道,也可参考 Presence 频道 )
Echo.private('ashuchatroom')
.listen('MessagePosted', (event) => {
// handle event
console.log("test echo", event);
});
class MessagePosted implements ShouldBroadcast
{
public $message;
public $user;
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(Message $message, User $user)
{
$this->message = $message;
$this->user = $user;
}
public function broadcastOn()
{
return new PrivateChannel('ashuchatroom'); // 与前端channel名称一致
}
}
Broadcast::channel('ashuchatroom', function () {
return true;
});
Broadcast::routes(['middleware' => ['web', 'auth']]);