Haɗin kai Laravel WebSocket tare da bayanan bayanai wani muhimmin sashi ne na gina aikace-aikace na lokaci-lokaci kamar Taɗi, sanarwar nan take, da bin diddigin aukuwa. Ta hanyar haɗawa WebSocket tare da bayanan bayanai, za mu iya adanawa da sarrafa bayanan ainihin lokaci yadda ya kamata. Anan ga yadda ake haɗawa Laravel WebSocket da bayanan bayanai.
Mataki 1: Shigar Laravel WebSocket Kunshin
Da farko, shigar kuma saita laravel-websockets
kunshin. Yi amfani da Mawaƙi don shigar da kunshin:
composer require beyondcode/laravel-websockets
Da zarar an shigar, kuna buƙatar buga fayilolin sanyi kuma kuyi ayyukan da suka dace:
php artisan vendor:publish --tag=websockets-config
php artisan migrate
Mataki 2: Ƙirƙiri Teburin Bayanai don Saƙonni
Za mu ƙirƙiri tebur a cikin ma'ajin bayanai don adana saƙonni. Yi amfani da umarni mai zuwa don ƙirƙirar messages
tebur:
php artisan make:model Message -m
Bayan gudanar da umarnin, za ku ga migration fayil da aka ƙirƙira a cikin database/migrations
kundin adireshi. Bude migration fayil ɗin kuma ayyana tsarin teburin messages
:
// database/migrations/xxxx_xx_xx_create_messages_table.php
public function up()
{
Schema::create('messages', function(Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->text('content');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Gudun migration umarni don ƙirƙirar tebur a cikin bayanan bayanai:
php artisan migrate
Mataki na 3: Sarrafa dagewar saƙo ta hanyar WebSocket
Lokacin da mai amfani ya aika saƙo, muna buƙatar mu riƙe kuma mu dage saƙon cikin ma'ajin bayanai. A cikin taron da aka aiko da saƙo, zaku iya amfani da Laravel Watsa shirye-shirye don aika saƙon WebSocket kuma a lokaci guda ajiye saƙon a cikin ma'ajin bayanai.
// app/Events/MessageSent.php
public function broadcastOn()
{
return new Channel('chat');
}
public function broadcastWith()
{
return [
'message' => $this->message,
'user' => $this->user,
];
}
// app/Listeners/SaveMessage.php
public function handle(MessageSent $event)
{
$message = new Message();
$message->user_id = $event->user->id;
$message->content = $event->message;
$message->save();
}
Kammalawa
Haɗin kai Laravel WebSocket tare da bayanan bayanai yana ba ku damar adanawa da sarrafa bayanan lokaci-lokaci yadda ya kamata. Ta haɗa WebSocket tare da bayanan bayanai, zaku iya gina hadaddun aikace-aikace na lokaci-lokaci kamar Chat, sanarwar gaggawa, da bin diddigin abubuwan cikin sassauƙa da ƙarfi.