Asked by Joney Spark · · 2 answers
Presence and Private Channel Not working in Laravel Sanctum SPA Authentication. It's only working in public channel.
#Please help me. I have been struggling last 7 days.
I am using Qiralab Sanctum Github Repo so here is no problem in authentication I think so.
Here is my github code: https://github.com/joneyspark/spa-chat-ws
- Websockets are configured and it's working public channel
#MessageSent.php
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct(Message $message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
#ChatsController.php
class ChatsController extends Controller
{
public function fetch_messages()
{
return Message::with('user')->get();
}
public function send_messages(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' => 'success'];
}
}
#channels.php
Broadcast::channel('chat', function ($user) {
return $user;
});
#BroadcastServiceProvider
class BroadcastServiceProvider extends ServiceProvider
{
public function boot()
{
Broadcast::routes(['middleware' => ['auth:sanctum']]);
require base_path('routes/channels.php');
}
}
#Vue CLI
import Echo from "laravel-echo";
import Request from "./apis/Request";
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
key: process.env.VUE_APP_WEBSOCKETS_KEY,
wsHost: process.env.VUE_APP_WEBSOCKETS_SERVER,
wsPort: 6001,
forceTLS: false,
disableStats: true,
enabledTransports: ["ws", "wss"],
authorizer: (channel, options) => {
console.log("OPTIONS>>", options);
return {
authorize: (socketId, callback) => {
Request.POST_REQ("/broadcasting/auth", {
socket_id: socketId,
channel_name: channel.name,
withCredentials: true,
})
.then((response) => {
callback(false, response.data);
console.log("RESPONSE>>", response);
})
.catch((error) => {
callback(true, error);
});
},
};
},
});
#Chat.vue
created() {
this.fetchMessages();
window.Echo.join("chat").listen("MessageSent", (event) => {
console.log(event.message);
this.messages.push(event.message);
});
},
#.env
VUE_APP_WEBSOCKETS_KEY = local
VUE_APP_WEBSOCKETS_SERVER = 127.0.0.1
0
2
It is going to take time to review the GitHub repository you have shared. I will see this in my free time.
Thanks