Build a fully functional real-time chat app where messages appear instantly for all participants — no page refresh needed.
php artisan install:broadcasting
# Choose Reverb when prompted
php artisan reverb:start
// app/Events/MessageSent.php
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public Message $message) {}
public function broadcastOn(): array
{
return [
new PrivateChannel('chat.' . $this->message->room_id),
];
}
public function broadcastWith(): array
{
return [
'id' => $this->message->id,
'body' => $this->message->body,
'user' => $this->message->user->name,
'avatar' => $this->message->user->avatar_url,
'timestamp' => $this->message->created_at->diffForHumans(),
];
}
}
class ChatRoom extends Component
{
public Room $room;
public string $body = '';
public Collection $messages;
public function mount(): void
{
$this->messages = $this->room->messages()
->with('user')
->latest()
->take(50)
->get()
->reverse();
}
#[On('echo-private:chat.{room.id},MessageSent')]
public function onMessageReceived(array $event): void
{
$this->messages->push((object) $event);
}
public function send(): void
{
$message = $this->room->messages()->create([
'user_id' => auth()->id(),
'body' => $this->body,
]);
broadcast(new MessageSent($message))->toOthers();
$this->body = '';
}
}
All Comments