我一直关注this guide,以使用Pusher创建聊天系统。它可以工作,但是刷新页面时我只会收到其他人的任何新消息,这很烦人。我已经尝试了很多方法,但是它们都没有真正解决问题。我真的觉得这是我忽略了的超级简单的事情。如果有人可以帮助我,那就太好了!
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MessageSent.php
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* User that sent the message
*
* @var User
*/
public $user;
/**
* Message details
*
* @var Message
*/
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(User $user, Message $message)
{
$this->user = $user;
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('chat');
}
public function broadcastAs()
{
return 'MessageSent';
}
}
app.js
el: '#app',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private('chat').listen('MessageSent', (e) => {
console.log(e);
this.sentMessages.push({
message: e.message.message,
user: e.user
});
});
},
methods: {
fetchMessages() {
axios.get('/messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('/messages', message).then(response => {
console.log(response.data);
});
}
}
});
当我刷新created()
时,页面刷新时, console.log
仅触发一次。另外,无论是否到达Echo.private()
中的console.log。
ChatsController.php
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Show chats
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('chat');
}
/**
* Fetch all messages
*
* @return Message
*/
public function fetchMessages()
{
return Message::with('user')->get();
}
/**
* Persist message to database
*
* @param Request $request
* @return Response
*/
public function sendMessage(Request $request)
{
$user = Auth::user();
$message = $user->messages()->create([
'message' => $request->input('message')
]);
broadcast(new MessageSent($user, $message))->toOthers();
return ['status' => 'Message Sent!'];
}
}
我还没有在 config / app.php
中注释 App \ Providers \ BroadcastServiceProvider答案 0 :(得分:0)
好的,我修复了它。我发现问题是由使用php artisan app:name <name here>
更改应用程序名称引起的。因此,我使用命令php app:name App