I am now exhausted, and as a final resort coming here. i have a management system with laravel and react. both will host separately but right now setup in Laragon, using auth:sanctum for auth, storing token in redux state.
I want to create a inbox feature where users within the same company can chat.
What i have done so far
Route::get('/conversations', [MessageController::class, 'conversations']);
Route::get('/messages/{user}', [MessageController::class, 'index']); //receive message
Route::post('/messages', [MessageController::class, 'store']); //send message
cors.php
'paths' => ['api/*', 'broadcasting/auth', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
channels.php
Broadcast::channel('chat.{userId}', function ($user, $userId) {
return (int) $user->id === (int) $userId;
});
in frontend;
in my inbox component
const echoRef = useRef(null);
window.Pusher = Pusher;
useEffect(() => {
if (!echoRef.current) {
echoRef.current = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_APP_REVERB_APP_KEY,
cluster: import.meta.env.VITE_APP_REVERB_CLUSTER,
disableStats: true,
forceTLS: false,
encrypted: false,
authEndpoint: `${import.meta.env.VITE_API_URL_ONLY}/broadcasting/auth`,
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
},
},
});
console.log("Echo instance initialized");
}
}, [token]); // Update only if token changes
.
.
.
const sendMessage = async (e) => {
e.preventDefault();
if (!newMessage.trim() || !activeChat) return;
try {
const response = await authAxios.post(`/messages`, {
receiver_id: activeChat.id,
content: newMessage,
});
// Add the message to the local state
setMessages((prev) => [...prev, response.data]);
// Send the message via WebSocket
echoRef.current?.private(`chat.${activeChat.id}`).whisper('NewMessage', response.data);
setNewMessage('');
} catch (error) {
console.error('Error sending message:', error);
}
};
but when i send message, it only stores in database and does not send to websocket.
i dont know why i did
authEndpoint: `${import.meta.env.VITE_API_URL_ONLY}/broadcasting/auth`,
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
},
},
do i need it or not, i dont know, i just blindly followed GPT, and online stuff.
i am constantly getting websocket connection failed with apparently no error.
another issue is with this /broadcasting/auth endpoint. which always go for CORS,
adding it in cors.php throws a bunch of more errors and error trace . but headline is
"exception": "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException",
i tried every AI i could use, it has been two weeks straight.. i cant get websockets to work. every other tutorial showing a basic channel app, or they use react with in the laravel it self. but I dont find my case.