ammar_ahmed started a new conversation+100 XP
4mos ago
I am implementing real-time broadcasting in Laravel 12 with React (Inertia) using Pusher and Laravel Echo.
The backend event fires successfully, but the frontend does not receive the broadcast. In the browser console, I consistently get the following error:
POST http://127.0.0.1:8000/broadcasting/auth 403 (Forbidden)
1. Route Where the Event Is Fired (web.php)
The event is triggered from a route using the authenticated user.
Route::get('/send-message', function () {
$userId = auth()->id();
$message = 'message from ' . auth()->user()->name;
event(new MessageSent($userId, $message));
return response()->json(['status' => 'Message sent']);
});
EvnentMessage
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public int $userId,
public string $message
) {}
public function broadcastOn(): array
{
return [
new PrivateChannel('chat.' . $this->userId),
];
}
public function broadcastAs(): string
{
return 'MessageSent';
}
}
Channel.php
Broadcast::channel('chat.{userId}', function ($user, $userId) {
return true;
});
Chat.tsx
Listening the event
import { SharedData } from '@/types';
import { usePage } from '@inertiajs/react';
import { useEcho } from '@laravel/echo-react';
export default function Chat() {
const { auth } = usePage<SharedData>().props;
const userId = auth?.user?.id;
useEcho(`chat.${userId}`, 'MessageSent', (e) => {
console.log(e.message);
});
return <div>Check console for messages!</div>;
}
App.tsx
import { configureEcho } from '@laravel/echo-react';
configureEcho({
broadcaster: 'pusher',
});