Kule tutorial, siya kwakha isicelo sencoko yexesha langempela sisebenzisa iLaravel, Nuxt 3, Sanctum, kunye neReverb yeLaravel ukuphatha imiyalezo ekhuselekileyo kunye nephilayo phakathi kwabasebenzisi. Siza kuseka ukuqinisekiswa komsebenzisi, ukudibanisa kwi-API ekhuselekileyo, kwaye siqinisekise ukuba i-chat updates ngoko nangoko ukwenzela amava agudileyo kwaye aphendule.
Siza kusebenzisa imodyuli ukulawula ukuqinisekiswa kwe-SPA, ephethe ngokufanelekileyo zombini iSicelo sePhepha elinye (SPA) kunye nokuqinisekiswa kwe-API. Ukufunda ngakumbi malunga nokusebenzisa le modyuli, jonga inqaku kwiNuxt 3 SPA ungqinisiso .
Kule projekthi, siya kumisela iReverb yeLaravel yokusasazwa komsitho wexesha lokwenyani, siphumeze ukuqinisekiswa ngeSanctum, kwaye sakhe i-Nuxt 3 frontend ebonisa ngamandla kwaye ilawule imiyalezo yencoko. Masiqalise!
Okokuqala, qinisekisa ukuba iLaravel Sanctum ifakiwe kwaye iqwalaselwe. I-Sanctum ivumela ukuqinisekiswa okusekelwe kwi-token kwizicelo zephepha elinye (SPA). Emva koko, faka kwaye uqwalasele i-Laravel Reverb yezakhono zexesha langempela.
Yongeza oku kulandelayo kwimo yendalo eguquguqukayo yeReverb kwifayile yakho .env
:
REVERB_APP_ID=my-app-id REVERB_APP_KEY=my-app-key REVERB_APP_SECRET=my-app-secret REVERB_HOST="localhost" REVERB_PORT=8080 REVERB_SCHEME=http
Ukugcina imiyalezo yencoko, yenza ukufuduka kwitheyibhile ye chat_messages
. Baleka:
php artisan make:migration create_chat_messages_table
Hlaziya ifayile yokufuduka ngolu hlobo lulandelayo:
Schema::create('chat_messages', function (Blueprint $table) { $table->id(); $table->foreignId('receiver_id'); $table->foreignId('sender_id'); $table->text('text'); $table->timestamps(); });
Qhuba umfuduko ukwenza itheyibhile:
php artisan migrate
Ukusasaza imiyalezo ngexesha lokwenyani, yenza iklasi yomsitho MessageSent
:
php artisan make:event MessageSent
Hlaziya iklasi yomsitho:
<?php namespace App\Events; use App\Models\ChatMessage; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class MessageSent implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public function __construct(public ChatMessage $message) { // } public function broadcastOn(): array { return [new PrivateChannel("chat.{$this->message->receiver_id}")]; } }
channels.php
, chaza ijelo losasazo:
Broadcast::channel('chat.{id}', function ($user, $id) { return (int) $user->id === (int) $id; });
Yongeza ezi ndlela ukuze ulawule ukuthumela kunye nokufumana imiyalezo yencoko:
Route::get('/messages/{user}', function (User $user, Request $request) { return ChatMessage::query() ->where(function ($query) use ($user, $request) { $query->where('sender_id', $request->user()->id) ->where('receiver_id', $user->id); }) ->orWhere(function ($query) use ($user, $request) { $query->where('sender_id', $user->id) ->where('receiver_id', $request->user()->id); }) ->with(['sender', 'receiver']) ->orderBy('id', 'asc') ->get(); })->middleware('auth:sanctum'); Route::post('/messages/{user}', function (User $user, Request $request) { $request->validate(['message' => 'required|string']); $message = ChatMessage::create([ 'sender_id' => $request->user()->id, 'receiver_id' => $user->id, 'text' => $request->message ]); broadcast(new MessageSent($message)); return $message; });
Ukuvumela i-Nux 3 ukuba iqhagamshelane neReverb, yongeza ezi ziguquguqukayo kwifayile yakho .env
:
NUXT_PUBLIC_REVERB_APP_ID=my-app-id NUXT_PUBLIC_REVERB_APP_KEY=my-app-key NUXT_PUBLIC_REVERB_APP_SECRET=my-app-secret NUXT_PUBLIC_REVERB_HOST="localhost" NUXT_PUBLIC_REVERB_PORT=8080 NUXT_PUBLIC_REVERB_SCHEME=http
Emva koko, zilayishe ku nuxt.config.ts
:
export default defineNuxtConfig({ runtimeConfig: { public: { REVERB_APP_ID: process.env.NUXT_PUBLIC_REVERB_APP_ID, REVERB_APP_KEY: process.env.NUXT_PUBLIC_REVERB_APP_KEY, REVERB_APP_SECRET: process.env.NUXT_PUBLIC_REVERB_APP_SECRET, REVERB_HOST: process.env.NUXT_PUBLIC_REVERB_HOST, REVERB_PORT: process.env.NUXT_PUBLIC_REVERB_PORT, REVERB_SCHEME: process.env.NUXT_PUBLIC_REVERB_SCHEME, }, }, });
Ukulawula uhlaziyo lwexesha lokwenyani, yenza iplagin laravel-echo.client.ts
:
import Echo from "laravel-echo"; import Pusher, { type ChannelAuthorizationCallback } from "pusher-js"; declare global { interface Window { Echo: Echo; Pusher: typeof Pusher; } } export default defineNuxtPlugin(() => { window.Pusher = Pusher; const config = useRuntimeConfig(); const echo = new Echo({ broadcaster: "reverb", key: config.public.REVERB_APP_KEY, wsHost: config.public.REVERB_HOST, wsPort: config.public.REVERB_PORT ?? 80, wssPort: config.public.REVERB_PORT ?? 443, forceTLS: (config.public.REVERB_SCHEME ?? "https") === "https", enabledTransports: ["ws", "wss"], authorizer: (channel, options) => ({ authorize: (socketId, callback) => { useSanctumFetch("api/broadcasting/auth", { method: "post", body: { socket_id: socketId, channel_name: channel.name }, }) .then(response => callback(null, response)) .catch(error => callback(error, null)); }, }), }); return { provide: { echo } }; });
Ukuvumela ingxoxo yexesha langempela kwi-app yethu ye-Nuxt 3, ndenze iphepha elitsha, chats > [id].vue
, apho abasebenzisi banokukhetha kwaye baxoxe nabanye abasebenzisi. Eli phepha lidibanisa kwi-backend ye-Laravel yokulawula imiyalezo yengxoxo kunye nedatha yomsebenzisi, usebenzisa i-Laravel Echo kunye ne-WebSockets yokuhlaziywa kwexesha langempela kunye nezikhombisi zokuchwetheza.
Nalu ucazululo lwendlela esiye sayimisa ngayo le ncoko:
Okokuqala, sifumana kwakhona i userID
kwi-URL kunye ne useRoute
composable. Le userID
ichonga umsebenzisi esincokola naye kwaye ilayishe umsebenzisi oyimfuneko kunye nemiyalezo yencoko.
const route = useRoute(); const userID = route.params.id; const { user: currentUser } = useSanctum<User>(); const { data: user } = await useAsyncData( `user-${userID}`, () => useSanctumFetch<User>(`/api/users/${userID}`) ); const { data: messages } = useAsyncData( `messages-${userID}`, () => useSanctumFetch<ChatMessage[]>(`/api/messages/${userID}`), { default: (): ChatMessage[] => [] } );
Le snippet isebenzisa useSanctumFetch
, isiko elinokuqulunqwa, ukulayisha imiyalezo ngokulandelelanayo xa iphepha linyuswa.
Sinikezela ngomyalezo ngamnye ngokuguquguqukayo, siwenza isimbo ngokusekelwe ekubeni usuka kumsebenzisi wangoku okanye umthathi-nxaxheba wengxoxo.
<div ref="messagesContainer" class="p-4 overflow-y-auto max-h-fit"> <div v-for="message in messages" :key="message.id" class="flex items-center mb-2"> <div v-if="message.sender_id === currentUser.id" class="p-2 ml-auto text-white bg-blue-500 rounded-lg"> {{ message.text }} </div> <div v-else class="p-2 mr-auto bg-gray-200 rounded-lg"> {{ message.text }} </div> </div> </div>
Ifestile yencoko iya kumyalezo wamva nje ngokuzenzekelayo isebenzisa nextTick()
.
watch( messages, () => { nextTick(() => messageContainerScrollToBottom()); }, { deep: true } ); function messageContainerScrollToBottom() { if (!messagesContainer.value) return; messagesContainer.value.scrollTo({ top: messagesContainer.value.scrollHeight, behavior: 'smooth' }); }
Abasebenzisi banokuthumela imiyalezo ngommandla wongeniso. Emva kokungeniswa, isicelo se-POST sithunyelwa kwi-backend ye-Laravel.
const newMessage = ref(""); const sendMessage = async () => { if (!newMessage.value.trim()) return; const messageResponse = await useSanctumFetch<ChatMessage>(`/api/messages/${userID}`, { method: "post", body: { message: newMessage.value } }); messages.value.push(messageResponse); newMessage.value = ""; };
Imiyalezo ihlaziywa ngoko nangoko emva kokuba ithunyelwe.
I-Laravel Echo imamele iziganeko eziphambili ezifana MessageSent
kunye typing
.
onMounted(() => { if (currentUser.value) { $echo.private(`chat.${currentUser.value.id}`) .listen('MessageSent', (response: { message: ChatMessage }) => { messages.value.push(response.message); }) .listenForWhisper("typing", (response: { userID: number }) => { isUserTyping.value = response.userID === user.value?.id; if (isUserTypingTimer.value) clearTimeout(isUserTypingTimer.value); isUserTypingTimer.value = setTimeout(() => { isUserTyping.value = false; }, 1000); }); } });
Oku kuphatha uhlaziyo lomyalezo wexesha lokwenyani kunye nezalathi zokuchwetheza, ezinyamalalayo emva kwesibini sokungasebenzi.
Ukubonisa isalathisi sokuchwetheza, siqalisa isiganeko "sokuchwetheza" whisper
.
const sendTypingEvent = () => { if (!user.value || !currentUser.value) return; $echo.private(`chat.${user.value.id}`).whisper("typing", { userID: currentUser.value.id }); };
Esi siganeko sithunyelwa nanini na umsebenzisi echwetheza, kwaye umamkeli ebona isalathisi sokuchwetheza.
Ujongano lwengxoxo lubandakanya iheader enegama lomsebenzisi okhethiweyo kunye namacandelo emiyalezo kunye nendawo yokufaka.
<template> <div> <header v-if="user" class="bg-white shadow"> <div class="px-4 py-6 mx-auto max-w-7xl sm:px-6 lg:px-8"> <h1 class="text-2xl font-bold ">{{ user.name }}</h1> </div> </header> <div class="flex flex-col items-center py-5"> <div class="container w-full h-full p-8 space-y-3 bg-white rounded-xl"> <div v-if="currentUser"> <div class="flex flex-col justify-end h-80"> <div ref="messagesContainer" class="p-4 overflow-y-auto max-h-fit"> <div v-for="message in messages" :key="message.id" class="flex items-center mb-2"> <div v-if="message.sender_id === currentUser.id" class="p-2 ml-auto text-white bg-blue-500 rounded-lg"> {{ message.text }} </div> <div v-else class="p-2 mr-auto bg-gray-200 rounded-lg"> {{ message.text }} </div> </div> </div> </div> <div class="flex-shrink-0"> <span v-if="user && isUserTyping" class="text-gray-500"> {{ user.name }} is typing... </span> <div class="flex items-center justify-between w-full p-4 border-t border-gray-200"> <input type="text" v-model="newMessage" @keydown="sendTypingEvent" @keyup.enter="sendMessage" class="w-full p-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Type a message..." /> <button @click.prevent="sendMessage" class="inline-flex items-center justify-center w-12 h-12 ml-4 text-white bg-blue-500 rounded-lg hover:bg-blue-600"> <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" /> </svg> </button> </div> </div> </div> </div> </div> </div> </template>
Oku kugqiba ukuseta inqaku lencoko yexesha lokwenyani usebenzisa iLaravel Sanctum kunye ne-Echo ngeNuxt 3.
Ngoku senze inkqubo yencoko ekhuselekileyo, yexesha lokwenyani sisebenzisa iLaravel, iSanctum, iReverb, kunye ne-Nuxt 3. Olu cwangciso lunokwenyuswa ngokulula ukuze luquke iimpawu ezongezelelweyo ezifana nempendulo yomyalezo okanye iingxoxo ezininzi.
Ngekhowudi epheleleyo, tyelela i -GitHub yokugcina .