我正在阅读本教程介绍 Laravel Echo。广播的事情正在完善。每当我执行命令时php artisan chat:message "something"
。事件被触发并将数据存储在数据库中。但是继续使用 Laravel Echo。我尝试了很多,但我无处可去。我已将 Echo 放入其中,/js/app.js
但在文档中提到了/js/bootstrap.js
. 由于我正在关注本教程,因此我将它放在/js/app.js
Echo 中,不会在日志中显示数据。我正在使用ubuntu
.
测试事件:
class TestEvent implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $message;
public $user;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user, $message)
{
//
$this->user = $user;
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return "chat-room";
}
}
发送聊天命令代码:
class SendChatMessage extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'chat:message {message}';
protected $description = 'Send chat message.';
public function handle()
{
// Fire off an event, just randomly grabbing the first user for now
$user = \App\User::first();
$message = \App\Message::create([
'user_id' => $user->id,
'content' => $this->argument('message')
]);
event(new \App\Events\TestEvent($message, $user));
}
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
}
Laravel 回声:
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'my-key'
});
window.Echo.channel('chat-room')
.listen('TestEvent', (e) => {
console.log(e.user, e.message);
});
每当我从推送者发送事件时,还有一件事。Pusher 能够正确发送。