I’m trying to create a laravel websocket using pusher + laravel-echo and vue+vite for frontend.
I used this guide for configuring websockets. The problem is that if I create an event on pusher Debug console with this params Channel: comments, Event: newComment
– it will console.log
this event on my site, but my real event isn’t showing.
This is my event:
class CommentCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
protected $comment;
public function __construct($comment)
{
$this->comment = $comment;
}
public function broadcastWith()
{
return [
'comment' => $this->comment,
];
}
public function broadcastAs()
{
return 'newComment';
}
public function broadcastOn()
{
return new Channel('comments');
}
}
I create this event in my CommentController.php
like this:
private function storeComment(Request $request)
{
$user = User::firstOrCreate(
['email' => $request['email']],
['username' => $request['username']]
);
$filePath = null;
if ($request->hasFile('file')) {
$file = $request->file('file');
$fileName = uniqid() . '.' . $file->getClientOriginalExtension();
$filePath = 'comments/' . $fileName;
$file->storeAs('comments', $fileName);
}
$comment = new Comment;
$comment->user_id = $user->id;
$comment->parent_id = $request->parent_id == 'null' ? null : $request->parent_id;
$comment->home_page = $request->homepage;
$comment->text = $request->text;
$comment->rating = 0;
$comment->file_path = $filePath;
$comment->created_at = now();
$comment->save();
event(new CommentCreated($request->get('comment'))); //event created
Cache::forget('comments_' . 'created_at' . '_desc' . '_1');
return response()->json("Comment saved", 201);
}
And on frontend I listen to event like this:
mounted() {
Echo.channel('comments')
.listen('.newComment', (comment) => {
console.log('New comment created:', comment);
});
}
I’m sure that problem is with event, not pusher configuration, otherwise if I created a new event on pusher debug console – it wouldn’t show on my site, so listening to event is configured correctly. I’m new to Laravel and I really hope that you would help me find what’s wrong. Thanks in advance 🙂
User is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.