Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P10)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P10): Users Get Unread Messages After Logging In

Next, we formally started to develop chat room chat functions.

After the user logs in, the unread messages need to be sent to the client to remind the user how many unread messages there are. Today we will write the front-end and back-end code around this function.

Front-end entry page logic

First, open at the front resources/js/pages/Load.vue, after the user logs will jump to the page, the Vue component mounted functions to achieve the following:

async mounted() {
    this.$store.commit("setTab", true);
    // Listen only once globally
    if (!this.isLogin) {
        // We are logged in and send entry information.
        if (this.userid) {
            // Handling unread messages
            socket.on("count", userCount => {
                this.$store.commit("setUnread", userCount);
                console.log(userCount);
            });
            this.$store.commit("setLoginState", true);
        }
    }
},

After the user first logs in successfully, the server will listen Websocket the count event, and returns the data to initialize the various chat rooms in the callback function depending on the service end unread messages.

The front-end code is relatively simple without any adjustments. Next, we go to the back-end to implement the corresponding code to obtain the number of unread messages.

Create related model classes and data tables

We create a new counts table to store user unread messages in each chat room.

Quick commands generated by Artisan Count model classes and the corresponding database migration categories:

php artisan make:model Count -m

Then modify the model class app/Count.php code as follows:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Count extends Model
{
    public static $ROOMLIST = [1, 2];
    public $timestamps = false;
}

Note: In order to simplify the logic here, we write the chat room data hard.

In the database/migrations directory just edit the migration class generated by CreateCountsTable the up method is as follows:

class CreateCountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('counts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id');
            $table->smallInteger('room_id');
            $table->integer('count')->default(0);
        });
    }
    
    ...

We counts define the four fields of the table, user_id indicates a user ID, room_idrepresents the room ID, count indicates the number of messages that the user does not read in this room.

Finally, run the database migration command to generate countsthe table:

php artisan migrate

Write Websocket routing implementation code

Open file Websocket route routes/websocket.php in login the route acquired unread messages written code is as follows:

WebsocketProxy::on('login', function (WebSocket $websocket, $data) {
    if (!empty($data['token']) && ($user = \App\User::where('api_token', $data['token'])->first())) {
        $websocket->loginUsing($user);
        // Get unread messages
        $rooms = [];
        foreach (\App\Count::$ROOMLIST as $roomid) {
            // Loop all rooms
            $result = \App\Count::where('user_id', $user->id)->where('room_id', $roomid)->first();
            $roomid = 'room' . $roomid;
            if ($result) {
                $rooms[$roomid] = $result->count;
            } else {
                $rooms[$roomid] = 0;
            }
        }
        $websocket->toUser($user)->emit('count', $rooms);
    } else {
        $websocket->emit('login', 'Login to enter chat room');
    }
});

We users, traversing all rooms unread message, and then count send it to the client conduit, if a client is listening this pipe, can read the message data and processed.

Test unread message initialization

Below we log in the user again in the browser, and we can see the Websocket communication information as follows:

This is image title

You can see the corresponding number of unread messages in Vue-> Vuex:

This is image title

At this point the data table is empty, so the data is 0, we can counts insert some test data in the table:

This is image title

Then log in and test again, you can see the number of unread messages:

This is image title

This is image title

#laravel #swoole #vue

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P10)
13.75 GEEK