Real-time chat room: realized by event broadcasting based on Laravel+Pusher+Vue.


I said before that I would sort out a tutorial on event broadcasting, but I finally had time to write this article today. This tutorial is based on Laravel+Pusher+Vue, with event broadcasting as the core technology, so that you can quickly build a real-time chat room application. Not much to say, let's take a look at the specific content directly. Application initialization

Installation configuration

First, install a brand-new chat room application through Composer:

composer create-project laravel/laravel chatroom --prefer-dist

Because of the event broadcast, you need to cancel the comments in front of the broadcast service provider in config/app.php:

Modify the BROADCAST_DRIVER configuration item in. env to pusher:


Although Laravel supports Pusher out of the box, we still need to install the corresponding PHP SDK:

composer require pusher/pusher-php-server

Set the Pusher voucher information

Visit Pusher official website, register and log in to the user background, and create a new Channels App:

After the creation is completed, you can get the relevant information of App Keys in the jump page:

Fill the corresponding field into the corresponding configuration item. env in the root directory of the chat room application.

Front-end resource initialization

We use Laravel Mix to compile front-end CSS and JavaScript:

npm install

In addition, Laravel also provides a JavaScript library Laravel Echo to subscribe and listen to events:

npm install --save laravel-echo pusher-js

After the installation is completed, we should also tell Laravel Echo to use Pusher. Laravel has provided us with this implementation in resources/assets/js/bootstrap.js, but it is commented by default, so just cancel this comment:

import Echo from 'laravel-echo' window.Pusher = require('pusher-js'); window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, cluster: process.env.MIX_PUSHER_APP_CLUSTER, encrypted: true });

User-certified scaffold code

We set that only logged-in users can enter the chat room to chat. In order to simplify the process, we use Laravel's default user authentication function:

php artisan make:auth

The above commands will generate the necessary routing, view, controller and other codes for the user authentication system. Before the function takes effect, you need to run the database migration command to generate the corresponding data table, edit the database-related configuration items in. env to ensure that you can connect to the database correctly, and then run the following command:

php artisan migrate

At this point, the preparation for application initialization has been completed, and the business code is now written.

Business code implementation

Message model

First, create a model class and its corresponding database migration file for the sent message:

php artisan make:model Message -m

Add the following line of code to the newly generated app/messagemodel class to facilitate batch assignment:

/** * Fields that are mass assignable * * @var array */ protected $fillable = ['message'];

Then write the up method of the migration file corresponding to the newly generated messages in the databases/migrations directory:

Schema::create('messages', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->text('message'); $table->timestamps(); });

Finally, execute the migration command to generate data table messages:

php artisan migrate

Relationship between users and messages

Obviously, there is a one-to-many relationship between Users and messages. Add an association method in the user model class:

/** * A user can have many messages * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function messages() { return $this->hasMany(Message::class); }

Next, define the relative relationship in the Message model class:

/** * A message belong to a user * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); }

Controller code

Create controller ChatsController to realize specific business logic;

php artisan make:controller ChatsController

Write the newly generated controller class app/http/controllers/chatscontroller code as follows:

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us