laravel 使用vue
It's been a while since I wrote about Laravel and thought I should do something fun with it. In this tutorial, I will show you how to build a web-based chat application using Laravel and Vue.js quickly. With a simple step by step guide, you will be able to create a system that supports user authentication and authorization before participating in a chat session.
自从我写了有关Laravel的文章以来,已经有一段时间了,我认为我应该对此做些有趣的事情。 在本教程中,我将向您展示如何使用Laravel和Vue.js快速构建基于Web的聊天应用程序。 借助简单的分步指南,您将能够创建一个支持用户身份验证和授权的系统,然后再参与聊天会话。
Due to the fact that Laravel is shipped with Vue.js by default, It is very easy to build single-page applications, handle frontend logic by creating Vue components and use them like you would use a regular HTML tag inside the blade template of Laravel.
由于默认情况下Laravel随Vue.js一起提供,因此很容易构建单页应用程序,通过创建Vue组件来处理前端逻辑并像使用Laravel刀片模板中的常规HTML标签一样使用它们。
To make this chat application fully functional, you will leverage CometChat chat infrastructure to enhance the sharing of instant messages.
为了使此聊天应用程序充分发挥功能,您将利用CometChat聊天基础结构来增强即时消息的共享。
At the end of this tutorial, you would have built a system that will allow users to send and receive messages in realtime, as shown below:
在本教程的最后,您将构建一个系统,该系统将允许用户实时发送和接收消息,如下所示:
To join a chat session, a user will have to provide a unique username
and password
as credentials during the registration process, afterward, such user will be created on CometChat as well. This means when registering a new user within your application, the details of such users will be saved in your local database first and then sent to the CometChat server using its REST API. Laravel will be used to build a backend API needed for these processes and make provisions of endpoints for Vue.js on the frontend.
要加入聊天会话,用户将必须在注册过程中提供唯一的username
和password
作为凭据,然后,还将在CometChat上创建该用户。 这意味着在应用程序中注册新用户时,这些用户的详细信息将首先保存在本地数据库中,然后使用其REST API发送到CometChat服务器。 Laravel将用于构建这些流程所需的后端API,并在前端为Vue.js设置端点。
If you would love to try out the working demo for this tutorial, you can download the complete source code here on GitHub.
如果您想尝试本教程的工作演示,可以在GitHub上下载完整的源代码。
Before proceeding, this tutorial assumes you have:
在继续之前,本教程假定您具有:
CometChat is a developer platform that allows you to easily integrate chat features and building a realtime chat widget for a new or existing web and mobile application. It is a developer tool that makes implementing features such as;
CometChat是一个开发人员平台,可让您轻松集成聊天功能并为新的或现有的Web和移动应用程序构建实时聊天小部件。 它是一个开发人员工具,可实现以下功能:
You can read more about CometChat here on Comet’s official website.
您可以在Comet的官方网站上了解有关CometChat的更多信息。
It is compulsory that one must be authenticated as a user before you can make use of infrastructure made available by CometChat.
必须强制经过身份验证的用户才能使用CometChat提供的基础结构。
As proof of concept or to test a demo application, you can make use of the sample users that are being generated automatically for every new application created on CometChat. But for a production-ready application, it is advisable to take it a step further by making use of our REST API to programmatically create unique users, as you would see later in the tutorial.
作为概念验证或测试演示应用程序,您可以利用为CometChat上创建的每个新应用程序自动生成的样本用户。 但是对于可用于生产环境的应用程序,建议您进一步使用REST API,以编程方式创建唯一用户,这将使您走得更远,就像您将在本教程的后面看到的那样。
Once a user is in place, authenticating such a user to CometChat, is as simple as calling the CometChat.login()
the method from the JavaScript SDK. Before this method can work properly, you can either use the user’s UID and the auth-only secret key as a parameter for the CometChat.login()
, or you can generate a unique auth token on CometChat via its REST API and use the generated token as they require a parameter.
一旦用户就位,对此类用户进行CometChat身份验证就像从JavaScript SDK调用CometChat.login()
方法一样简单。 在此方法正常工作之前,您可以将用户的UID和仅身份验证密钥用作CometChat.login()
的参数,也可以通过CometChat的REST API生成唯一的身份验证令牌,然后使用生成的令牌,因为它们需要参数。
For the purpose of this tutorial, you will learn how to use the auth token for authenticating a user.
就本教程而言,您将学习如何使用auth令牌来认证用户。
While CometChat can handle the login process of users from your application, It is important to note that CometChat SDK can only maintain the session of the logged-in user within the SDK and will not be able to handle user authentication for your application. So here, you will build an authentication server using Laravel.
尽管CometChat可以处理您应用程序中用户的登录过程,但需要注意的是CometChat SDK只能维护SDK中已登录用户的会话,而不能处理应用程序的用户身份验证。 因此,在这里,您将使用Laravel构建身份验证服务器。
The get started easily, you are going to set up a group chat application on top of a Laravel 5.8 application on GitHub. This starter template already contains the required assets, stylesheet, and a couple of dependencies for the app.
轻松入门,您将在GitHub上的Laravel 5.8应用程序之上设置一个群聊应用程序。 该入门模板已经包含所需的资产,样式表以及该应用程序的几个依赖项。
You will be making use of Git to clone this repository and gradually add more code to make it fully functional.
您将利用Git克隆此存储库,并逐步添加更多代码以使其完全起作用。
To begin, from the terminal in your machine, navigate to your preferred project directory and run the following command to clone the starter template from GitHub:
首先,从您机器上的终端,导航到您的首选项目目录,然后运行以下命令从GitHub克隆入门模板:
// Clone repositorygit clone https://github.com/christiannwamba/lara-chat-app-starter.git
Next, move into the newly created project:
接下来,进入新创建的项目:
cd lara-chat-app-starter
and install all the dependencies for Laravel using composer by running the following command:
并通过运行以下命令使用composer安装Laravel的所有依赖项:
composerinstall
Now, create a .env
file and then copy the content of .env.example
into it:
现在,创建一个.env
文件,然后将.env.example
的内容复制到其中:
// create a .envfile
touch .env
// update its content
cp .env.example .env
Generate a key for your project using the artisan
command:
使用artisan
命令为您的项目生成密钥:
php artisan key:generate
Once you are done, the next step is to create a connection to your database. To achieve that, open the .env
file and update the DB_DATABASE
, DB_USERNAME
and DB_PASSWORD
values with the appropriate contents.
完成后,下一步就是创建与数据库的连接。 为此,请打开.env
文件,并使用适当的内容更新DB_DATABASE
, DB_USERNAME
和DB_PASSWORD
值。
To avoid running into any error, ensure that you have created a database before running the next command.
为了避免遇到任何错误,请确保在运行下一个命令之前已创建数据库。
After successfully completing this basic setup, you can now proceed to generate the database structure for your application using the following command:
成功完成此基本设置之后,您现在可以使用以下命令继续为您的应用程序生成数据库结构:
php artisan migrate
The preceding command will run the migration file located in database/migrations/
with a file name that looks like this 2014_10_12_000000
_create_users_table.php`` and create aUsers\
table with the appropriate fields.
前面的命令将运行位于database/migrations/
的迁移文件,其文件名如下所示: 2014_10_12_000000
_create_users_table.php``并使用适当的字段创建Users\
表。
In chronological order, what you want to achieve with the backend of this application is to create endpoints with the purpose of handling three different functionalities:
按照时间顺序,您希望使用此应用程序的后端实现的目的是创建端点,以处理三种不同的功能:
Since the intention is to build the backend as an API that will be consumed by Vue.js (Frontend), it is absolutely fine to make use of the routes specifically created for that purpose by Laravel. First, open the routes/web.php
file and ensure that the content in it is the same as what you have below. Otherwise, update its content with:
由于目的是将后端构建为Vue.js(Frontend)将使用的API,因此绝对可以使用Laravel为此目的专门创建的路由。 首先,打开routes/web.php
文件,并确保其中的内容与下面的内容相同。 否则,请使用以下命令更新其内容:
// routes/web.php
Route::get('/{any}', function () {
return view('layouts.master');
})->where('any','.*');
The code snippet above was used to register a route that can respond to all HTTP verbs. This is ideal for this application as all the routing will be handled by Vue.js, and Laravel will only render a single master layout view named layouts.master
. You will create this file in a bit. Next, in routes/api.php
, add the following routes to the list:
上面的代码段用于注册可以响应所有HTTP动词的路由。 这对于该应用程序是理想的,因为所有路由都将由Vue.js处理,并且Laravel将仅呈现一个名为layouts.master
主布局视图。 您将稍后创建此文件。 接下来,在routes/api.php
,将以下路由添加到列表中:
// routes/web.php
Route::post('/register', 'UserController@register')->middleware('guest');
Route::post('/login', 'UserController@login')->middleware('guest');
Route::post('/update/token', 'UserController@updateToken');
From your terminal, ensure that you are still within the root directory of the application and run the following command that will create a new UserController
:
在终端上,确保您仍在应用程序的根目录中,并运行以下命令将创建一个新的UserController
:
php artisan make:controller UserController
You will see the following output in the terminal:
您将在终端中看到以下输出:
Controller created successfully
This will automatically generate a new file named UserController.php
located in app/Http/UserController.php
. Inside this controller class, you will add the following methods to match your project routes: register
, login
, updateToken
.
这将自动在app/Http/UserController.php
生成一个名为UserController.php
的新文件。 在此控制器类内,您将添加以下方法以匹配您的项目路线: register
, login
和updateToken
。
Register a user Here, you will implement the logic to register a user for your application. Open the newly created app/Http/Controllers/UserController.php
and update its content with the following:
注册用户在这里,您将实现为应用程序注册用户的逻辑。 打开新创建的app/Http/Controllers/UserController.php
并使用以下内容更新其内容:
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function register(Request $request) {
$username = $request->get('username');
$password = $request->get('password');
if ($this->checkIfUserExist($username)) {
return response()->json([
'message' => 'User already exist'
], 500);
} else {
$password = bcrypt($password);
User::create([
'username' => $username,
'password' => $password
]);
return response()->json(true);
}
}
private function checkIfUserExist($username) {
$user = User::where('username', $username)->first();
if ($user) {
return $user;
} else {
return false;
}
}
}
The method above uses Laravel’s Request method to obtain the username
and password
of a particular user. And then, there is a check carried out to note if such a user exists in the database by calling a private method checkIfUserExist()
, which will either return the User
object if it exist or false
if otherwise.
上面的方法使用Laravel的Request 方法来获取特定用户的用户username
和password
。 然后,通过调用私有方法checkIfUserExist()
进行检查以记录该用户是否存在于数据库中,该方法将返回User
对象(如果存在checkIfUserExist()
,否则返回false
。
Authenticate the user within the application Now add the login()
to handle the authentication of users within the application:
在应用程序中对用户进行身份验证现在添加login()
来处理应用程序中的用户身份验证:
public function login(Request $request) {
$username = $request->get('username');
$password = $request->get('password');
$user = $this->checkIfUserExist($username);
if ($user) {
$confirmPassword = Hash::check($password, $user->password);
return response()->json([
'status' => $confirmPassword,
'token' => $user->authToken
]);
} else {
return response()->json([
'message' => "Invalid credentials"
], 500);
}
}
Here, after grabbing the username
and password
of a particular user, you checked if the user exists in your project’s database. If found, you will confirm to ensure that the password hash matches the one that was provided by the user and then returns the auth token that was generated for the user during the registration process.
在这里,获取特定用户的username
和password
后,您检查了该用户是否存在于项目的数据库中。 如果找到,您将确认以确保密码哈希与用户提供的密码哈希匹配,然后返回在注册过程中为用户生成的身份验证令牌。
Save Users’ token in the database One of the approaches to authenticate users in CometChat is by calling the CometChat.login()
and passing a generated token
to it as an argument. CometChat already made a provision to generate that on the fly through the REST API without much hassle. You will do that once you start the implementation of the frontend logic. To save the generated token for each user, add the following method to the UserController
:
在数据库中保存用户的令牌在 CometChat中对用户进行身份验证的方法之一是调用CometChat.login()
并将生成的token
作为参数传递给它。 CometChat已经做好了通过REST API快速生成该请求的规定。 一旦开始前端逻辑的实现,就将执行此操作。 要保存为每个用户生成的令牌,请将以下方法添加到UserController
:
public function updateToken(Request $request) {
$username = $request->get('uid');
$token = $request->get('token');
User::where('username', $username)->update([
'authToken' => $token
]);
}
This will receive the generated Auth token
for the user by CometChat and use Laravel eloquent to update the Database with the value.
这将接收CometChat为用户生成的Auth token
,并雄辩地使用Laravel用值更新数据库。
Ensure that the file located in resources/views/layouts/master.blade.php
contains the following contents:
确保位于resources/views/layouts/master.blade.php
中的文件包含以下内容:
<!-- resources/views/layouts/master.blade.php -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{
{ csrf_token() }}">
<link rel="stylesheet" href="{
{ asset('css/style.css') }}">
<title>Laravel Chat Application</title>
</head>
<body>
<div id="app">
<App />
</div>
<script src="{
{ asset('js/app.js') }}"></script>
</body>
</html>
This is a basic HTML template with a link to the stylesheet and JavaScript file for the application. Also, a custom HTML tag
representing the markup to render the AppComponent in the resources/js/App.vue
files. The AppComponent
is the entry point of the Vue.js application. More about this later in the tutorial.
这是一个基本HTML模板,带有指向应用程序的样式表和JavaScript文件的链接。 另外,一个自定义HTML标记
表示标记,用于在resources/js/App.vue
文件中呈现resources/js/App.vue
。 AppComponent
是Vue.js应用程序的入口点。 本教程后面的内容将对此进行更多介绍。
Now that you are done setting up the contents required for the Backend, you can now proceed to create the structure for the frontend of the application.
既然您已经完成了设置后端所需的内容,那么现在可以继续为应用程序的前端创建结构了。
Earlier, you started this project by downloading a starter template from GitHub. As mentioned, it contains some dependencies that you need to install for this application before you can proceed. You have already installed the dependencies for the Backend and now open another terminal from your project’s directory and run the following command to install the dependencies for the frontend using NPM:
之前,您是通过从GitHub下载入门模板来启动该项目的。 如前所述,它包含一些必须为此应用程序安装的依赖项,然后才能继续。 您已经安装了后端的依赖关系,现在从项目目录中打开另一个终端,然后运行以下命令以使用NPM安装前端的依赖关系:
// install dependencies
npm install
Here is a list of some of the dependencies that will be installed from your package.json
file:
这是将从package.json
文件中安装的一些依赖项的列表:
vue
: Vue.js for building a single page application. vue
:用于构建单页应用程序的Vue.js。 axios
: A promise-based HTTP client for the browser axios
:浏览器的基于promise的HTTP客户端 @cometchat-pro/chat
: This is the JavaScript SDK for CometChat @cometchat-pro/chat
:这是CometChatJavaScript SDK vue-router
: This is the official router for Vue.js vue-router
:这是Vue.js的官方路由器 Create a CometChat account To be able to use and integrate CometChat into your application, you need to create an account. Head over to CometChat website and create a free CometChat Pro account. Once you fill all the required information, you will have a trial account set up for you immediately. Now, proceed to your CometChat dashboard, then add a new app by choosing the stable version of CometChat SDK (v2) and select your preferred region, as it will be used as it will be required when initializing CometChat within your project, I have selected Europe
for this tutorial. Next, enter a name for your app, then click on the +
sign and wait for a couple of seconds for your new app to be created.
创建一个CometChat帐户为了能够使用CometChat并将其集成到您的应用程序中,您需要创建一个帐户。 前往CometChat网站并创建一个免费的CometChat Pro帐户 。 填写所有必需的信息后,您将立即为您设置一个试用帐户。 现在,进入您的CometChat仪表板 ,然后通过选择稳定版本的CometChat SDK(v2)添加一个新应用并选择您的首选区域,因为在您的项目中初始化CometChat时将需要使用该区域,因此我选择了Europe
本教程。 接下来,为您的应用输入名称,然后单击+
号,并等待几秒钟以创建新应用。
Once your application is successfully created, click on Explore to open it and then go to the API Keys tab, copy both your APP ID and API Key (with full access scope) and save it somewhere. Also, by default, CometChat will automatically create a group with a unique GUID
for your app. Click on Groups tab to access it and copy it as well.
成功创建应用程序后,单击“ 浏览”将其打开,然后转到“ API密钥”选项卡,同时复制您的APP ID和API密钥 (具有完全访问权限)并将其保存在某个位置。 另外,默认情况下,CometChat会自动为您的应用创建一个具有唯一GUID
的组。 单击“ 组”选项卡以访问它并复制它。
Next, back in your Laravel application, open the .env
file and locate these variables:
接下来,返回您的Laravel应用程序,打开.env
文件并找到以下变量:
MIX_COMMETCHAT_API_KEY=YOUR_COMMETCHAT_API_KEY
MIX_COMMETCHAT_APP_ID=YOUR_COMMETCHAT_APP_ID
MIX_COMMETCHAT_GUID=YOUR_COMMETCHAT_GUID
Replace the YOUR_COMMETCHAT_API_KEY
, YOUR_COMMETCHAT_APP_ID
, YOUR_COMMETCHAT_GUID
placeholder with the appropriate credentials as obtained from your CometChat dashboard. With that out of the way, you can now start setting up the group chat.
用从CometChat仪表板获得的适当凭据替换YOUR_COMMETCHAT_API_KEY
, YOUR_COMMETCHAT_APP_ID
, YOUR_COMMETCHAT_GUID
占位符。 现在,您可以开始设置群聊了。
It is recommended by CometChat that your application must call the init()
method from the JavaScript SDK once your app starts. This will enable your app to communicate with the CometChat server easily. To achieve that, navigate to resources/js/App.vue
file and update the script section with the following code:
CometChat建议您的应用程序启动后,您的应用程序必须从JavaScript SDK调用init()
方法。 这将使您的应用轻松与CometChat服务器通信。 为此,请导航到resources/js/App.vue
文件,并使用以下代码更新脚本部分:
// resources/js/App.vue
Here, you initialise CometChat with your unique APP_ID
and REGION
.
在这里,您使用唯一的APP_ID
和REGION
初始化CometChat。
If you chose the US as your region, write setRegion(“us”) instead of setRegion(“eu”) as did above
如果您选择美国作为您的区域,请像上面一样写setRegion(“ us”)而不是setRegion(“ eu”)
The approach for this application is to register a user into your application and immediately create the same user programmatically in CometChat. You will achieve all these by using the REST API provided by CometChat once the registration process is successful within your application.
此应用程序的方法是将用户注册到您的应用程序中,并立即在CometChat中以编程方式创建该用户。 一旦在应用程序中成功完成注册过程,您将使用CometChat提供的REST API来实现所有这些目标。
To begin, you will create a new folder named views
within resources/js
folder. And within the newly created folder, create a new file and call it Register.vue
. Open it and update its section with the following content:
首先,您将在resources/js
文件夹中创建一个名为views
的新文件夹。 在新创建的文件夹中,创建一个新文件,并将其命名为Register.vue
。 打开它并使用以下内容更新其部分:
// resources/js/views/Register.vue
Do you have an account? Log in
The code snippet above contains input fields that will be used to obtain the username
, password
, and password_confirmation
of a user during the registration process. The HTML form will call a method named registerAppUser()
once submitted.
上面的代码段包含输入字段,这些字段将用于在注册过程中获取username
, password
和password_confirmation
。 提交后,HTML表单将调用名为registerAppUser()
的方法。
Now, within the section of the Register Component, paste the following code:
现在,在“注册组件”的部分中,粘贴以下代码:
// resources/js/views/Register.vue
Above, you defined the properties and corresponding initial values within the data option and then created the registerAppUser()
method. This method obtained the username
and password
of a user and used axios
to send it to the backend (Laravel). Once the user’s details are saved successfully, the backend API will return a successful response.
上面,您在data选项中定义了属性和相应的初始值,然后创建了registerAppUser()
方法。 此方法获取username
和password
,并使用axios
将其发送到后端(Laravel)。 成功保存用户的详细信息后,后端API将返回成功的响应。
If the registration process was successful, a new method to programmatically create the user on CometChat would be called.
如果注册过程成功,则将调用在CometChat上以编程方式创建用户的新方法。
Create a user on CometChat
在CometChat上创建一个用户
Add the following method to create the user on CometChat:
添加以下方法在CometChat上创建用户:
// resources/js/views/Register.vue
async createUserOnCometChat(username) {
let url = `https://api-eu.cometchat.io/v2.0/users`;
let data = {
uid: username,
name: `${username} sample`,
avatar: 'https://data-eu.cometchat.io/assets/images/avatars/captainamerica.png',
};
try {
const userResponse = await fetch(url, {
method: 'POST',
headers: new Headers({
appid: process.env.MIX_COMMETCHAT_APP_ID,
apikey: process.env.MIX_COMMETCHAT_API_KEY,
'Content-Type': 'application/json'
}),
body: JSON.stringify(data),
});
const userJson = await userResponse.json();
console.log('New User', userJson);
this.createAuthTokenAndSaveForUser(username);
this.redirectToLogin();
} catch (error) {
console.log('Error', error);
}
}
This method takes the username of the registered user after a successful sign-up process and passes it along with a custom name to CometChat Create User API. After the user has been created successfully, another method to create an auth via the CometChat API for the new user was also invoked.
成功注册后,此方法将使用注册用户的用户名,并将其与自定义名称一起传递给CometChat Create User API 。 成功创建用户后,还调用了另一种通过CometChat API为新用户创建身份验证的方法。
Creating a new CometChat auth token Add the method below to create an auth token for the user and the token in your database once the process is completed:
创建新的CometChat身份验证令牌添加该方法以在完成该过程后为用户和数据库中的令牌创建身份验证令牌:
// resources/js/views/Register.vue
async createAuthTokenAndSaveForUser(uid) {
let url = `https://api-eu.cometchat.io/v2.0/users/${uid}/auth_tokens`;
try {
const tokenResponse = await fetch(url, {
method: 'POST',
headers: new Headers({
appid: process.env.MIX_COMMETCHAT_APP_ID,
apikey: process.env.MIX_COMMETCHAT_API_KEY,
'Content-Type': 'application/json'
}),
});
const tokenJSON = await tokenResponse.json();
this.addUserToAGroup(uid);
this.sendTokenToServer(tokenJSON.data.authToken, tokenJSON.data.uid);
} catch (error) {
console.log('Error Token', error);
}
}
Add user to a group CometChat has already created members for the default group for your application automatically. So, before users that are created through your Laravel application can participate in a chat session, they need to be added as a member. Use the following method to add users of your application to a group:
将用户添加到组 CometChat已经为您的应用程序的默认组自动创建了成员。 因此,在通过Laravel应用程序创建的用户可以参与聊天会话之前,需要将他们添加为成员。 使用以下方法将您的应用程序的用户添加到组中:
// resources/js/views/Register.vue
async addUserToAGroup(uid) {
let url = `https://api-eu.cometchat.io/v2.0/groups/${process.env.MIX_COMMETCHAT_GUID}/members`;
let data = {
"participants":[uid]
};
try {
const groupResponse = await fetch(url, {
method: 'POST',
headers: new Headers({
appid: process.env.MIX_COMMETCHAT_APP_ID,
apikey: process.env.MIX_COMMETCHAT_API_KEY,
'Content-Type': 'application/json'
}),
body: JSON.stringify(data),
});
const groupJson = await groupResponse.json();
console.log('Added to group', groupJson);
} catch (error) {
console.log('Error', error);
}
},
Save AuthToken in database Having generated an AuthToken
for your app users on CometChat, you need to save the token in the database for that particular user. With this in place, the token can be retrieved as part of the user's details when authenticating the user within your application. Add the method below for that purpose:
将AuthToken保存在数据库中在AuthToken
为您的应用程序用户生成了AuthToken
之后,您需要将特定用户的令牌保存在数据库中。 有了这个,在应用程序内对用户进行身份验证时,可以将令牌作为用户详细信息的一部分进行检索。 为此添加以下方法:
// resources/js/views/Register.vue
sendTokenToServer(token, uid) {
axios.post(`http://localhost:8000/api/update/token`, {token, uid})
.then(response => {
console.log("Token updated successfully", response);
}).catch(error => {
alert(error.response.data.message);
})
}
Since you can now register users, create such users on CometChat and add them as a member of a particular group through your application, you will now proceed to authenticate users within your application and also on CometChat.
由于您现在可以注册用户,在CometChat上创建此类用户并通过您的应用程序将其添加为特定组的成员,因此您现在将继续在应用程序以及CometChat上对用户进行身份验证。
To begin, create a new file within resources/js/views
folder and name it Login.vue
. Open the newly created file and update the section with the following code:
首先,在resources/js/views
文件夹中创建一个新文件,并将其命名为Login.vue
。 打开新创建的文件,并使用以下代码更新部分:
// resources/js/views/Login.vue
Don't have an account? Register
Here, the HTML form will receive the inputted value for the username
and password
of a user and send it to be processed by the authLoginAppUser()
method once the form is submitted. Next, use the content below to update the section of the Login component:
在此,HTML表单将接收username
和password
的输入值,并在表单提交后将其发送给authLoginAppUser()
方法进行处理。 接下来,使用以下内容更新“登录”组件的部分:
// resources/js/views/Login.vue
The authLoginAppUser()
method will receive the username
and password
of a user and use axios to post it to the backend API for authentication. If the credential inputted by the user is correct, the authToken
generated for such user during the registration process will be retrieved and returned as part of the JSON response for further usage.
authLoginAppUser()
方法将接收username
和password
,并使用axios将其发布到后端API进行身份验证。 如果用户输入的凭据正确,那么将检索并在注册过程中为该用户生成的authToken
作为JSON响应的一部分返回,以供进一步使用。
The returned authToken
will now be used to log the user in on CometChat. Add the following method, immediately after the authLoginAppUser
for that purpose:
返回的authToken
现在将用于在CometChat上登录用户。 为此,请在authLoginAppUser
之后立即添加以下方法:
logUserInToCometChat(token) {
this.showSpinner = true;
CometChat.login(token).then(
() => {
this.showSpinner = false;
console.log("successfully login user");
this.$router.push({
name: 'chat',
params: {username: this.username, authenticated: true}
});
},
error => {
this.showSpinner = false;
alert("Whops. Something went wrong. This commonly happens when you enter a username that doesn't exist. Check the console for more information");
this.$router.push({
name: 'login',
params: {username: this.username, authenticated: true}
});
console.log("Login failed with error:", error.code);
}
);
},
Here, you called the login()
method from CometChat SDK and passed the authToken
of the user to it as a parameter. Once the user has been authenticated successfully, you will redirect the user to the Chat page by using Vue Router, which handles navigation for the application. Otherwise, a prompt with the appropriate message of why the process failed will be displayed, and the user will be redirected back to the login page.
在这里,您从CometChat SDK调用了login()
方法,并将用户的authToken
作为参数传递给它。 成功验证用户身份后,您将使用Vue路由器将用户重定向到“聊天”页面,该路由器处理应用程序的导航。 否则,将显示一个提示,提示有关过程失败的原因的相应消息,并将用户重定向到登录页面。
Create a new file named Chat.vue
within the resources/js/views
and update the section with the following content:
在resources/js/views
创建一个名为Chat.vue
的新文件,并使用以下内容更新部分:
// resources/js/views/Chat.vue
#General
No new message?
Send your first message below.
{
{ message.sender.uid }}
{
{ message.data.text }}
{
{ message.data.text }}
The chat view will house all the logic required to interact with the CometChat API to implement the chat functionality, which is the core feature of your application. Here, we will get the details of the logged-in user, implement a method to send and receive messages from a group chat, and also fetch all previous messages sent by a user.
聊天视图将包含与CometChat API交互以实现聊天功能所需的所有逻辑,这是应用程序的核心功能。 在这里,我们将获取已登录用户的详细信息,实现一种从群聊中发送和接收消息的方法,以及获取用户以前发送的所有消息。
Here, once a user is authenticated and redirected to the chat page, you will receive the user details and display the unique username, avatar, and also an empty chat page for users who just joined a new group with no previous messages.
在这里,对用户进行身份验证并将其重定向到聊天页面后,您将收到用户详细信息,并显示唯一的用户名,头像和一个空的聊天页面,供刚刚加入新群组但没有以前消息的用户使用。
Also included is a form with an input field that will be used by a user to send a message to a group. The form will be processed by a method that will be implemented later in this section named sendGroupMessage()
.
还包括带有输入字段的表单,用户将使用该表单将消息发送到组。 表单将通过将在本节稍后部分实现的方法sendGroupMessage()
。
Get the logged in user details You will retrieve the details of the currently logged in user by calling a method named getLoggedInUser()
. This will return a User object containing all the information related to the logged-in user. Begin by adding this section to this component. Place the contents below within the
Chat.vue
immediately after the closing tag of the section:
获取登录的用户详细信息您将通过调用名为getLoggedInUser()
的方法来检索当前登录的用户的详细信息。 这将返回一个User对象,其中包含与已登录用户有关的所有信息。 首先将此部分添加到此组件。 将内容放在
部分的结束标记之后的
Chat.vue
:
// resources/js/views/Chat.vue
Once the details of the currently authenticated user are retrieved, the name, the avatar (if any), and unique user Id will also be updated. Otherwise, the user will be redirected to the login page
一旦检索到当前已认证用户的详细信息,名称,头像(如果有)和唯一用户ID也将被更新。 否则,用户将被重定向到登录页面
Send new messages Add the method below to implement the logic to send a new message to CometChat server during a group chat session:
发送新消息添加以下方法,以实现在群聊会话期间向CometChat服务器发送新消息的逻辑:
sendGroupMessage() {
this.sendingMessage = true;
var receiverID = process.env.MIX_COMMETCHAT_GUID;
var messageText = this.chatMessage;
var receiverType = CometChat.RECEIVER_TYPE.GROUP;
var textMessage = new CometChat.TextMessage(
receiverID,
messageText,
receiverType
);
CometChat.sendMessage(textMessage).then(
message => {
console.log("Message sent successfully:", message);
this.chatMessage = "";
this.sendingMessage = false;
this.$nextTick(() => {
this.scrollToBottom()
})
},
error => {
console.log("Message sending failed with error:", error);
}
);
}
Here, you called the sendMessage()
method and passed a constructed TextMessage()
to it. The TextMessage
class constructor takes the GUID
, messageText
and receiverType
as parameters. Receive incoming messages and Fetch previous messages Lastly, add the following method to receive real-time incoming messages posted to a group by its participants:
在这里,您调用了sendMessage()
方法并将一个构造的TextMessage()
传递给它。 TextMessage
类的构造函数将GUID
, messageText
和receiverType
作为参数。 接收传入消息并获取以前的消息最后,添加以下方法以接收其参与者发布到组的实时传入消息:
export default {
...
mounted() {
this.loadingMessages = true
var listenerID = "UNIQUE_LISTENER_ID";
const messagesRequest = new CometChat.MessagesRequestBuilder()
.setLimit(100)
.build()
messagesRequest.fetchPrevious().then(
messages => {
console.log("Message list fetched:", messages);
console.log("this.groupMessages", this.groupMessages)
this.groupMessages = [
...this.groupMessages,
...messages
];
this.loadingMessages = false
this.$nextTick(() => {
this.scrollToBottom();
})
},
error => {
console.log("Message fetching failed with error:", error);
}
);
CometChat.addMessageListener(
listenerID,
new CometChat.MessageListener({
onTextMessageReceived: textMessage => {
console.log("Text message received successfully", textMessage);
// Handle text message
console.log(this.groupMessages)
this.groupMessages = [
...this.groupMessages,
textMessage
];
this.loadingMessages = false
this.$nextTick(() => {
this.scrollToBottom();
})
}
})
);
}
};
An event listener that takes a unique listenerID as a parameter was registered to listen for messages when your app is running. Lastly, once a user logs in, the MessagesRequestBuilder
will be used to fetch any previous messages from the group and update the view with it.
已注册一个具有唯一listenerID作为参数的事件侦听器,以在您的应用程序运行时侦听消息。 最后,用户登录后,将使用MessagesRequestBuilder
来从组中获取任何先前的消息并使用该视图更新视图。
Now, in order to render a component for each given path, you will update the generated router file within the project. Open the router file located in .resources/js/routes.js
and replace its content with the following:
现在,为了渲染每个给定路径的组件,您将更新项目中生成的路由器文件。 打开位于.resources/js/routes.js
的路由器文件,并将其内容替换为以下内容:
// resources/js/routes.js
import Vue from 'vue';
import VueRouter from "vue-router";
import Login from './views/Login';
import Register from "./views/Register";
import Chat from "./views/Chat";
Vue.use(VueRouter);
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'homepage',
redirect: 'login'
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
{
path: '/chat',
name: 'chat',
component: Chat,
},
{
path: '*',
name: 'Not found',
redirect: 'login'
}
]
})
You successfully map each route within your application to the respective component that will handle the logic. This is a basic format of configuring Vue Router for a Vue.js application.
您已成功将应用程序中的每个路由映射到将处理逻辑的相应组件。 这是为Vue.js应用程序配置Vue路由器的基本格式。
Navigate to resources/js/app.js
and confirm that its content is the same as what you have below. If otherwise, feel free to update its content with this:
导航到resources/js/app.js
并确认其内容与下面的内容相同。 否则,请随时使用以下内容更新其内容:
// resources/js/app.js
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from "vue-router";
import App from './App.vue';
import routes from "./routes";
Vue.use(VueRouter);
const app = new Vue({
el: '#app',
router: routes,
components: {
App}
});
Here, you imported Vue, Vue Router library, and the routes file. You then proceeded to create a Vue instance and pass both the router and application components to it.
在这里,您导入了Vue,Vue路由器库和路由文件。 然后,您继续创建Vue实例,并将路由器和应用程序组件都传递给它。
If you have followed the tutorial up until now, well done! You have successfully built a group chat application with authentication using Laravel and Vue.js. To test all the implementation and be certain that it works as designed, open two different terminals, and ensure that you are within the project’s directory. Run the backend application from one of the terminals using the following command:
如果您到目前为止一直在学习本教程,那就做得很好! 您已经使用Laravel和Vue.js成功地构建了带有身份验证的群聊应用程序。 要测试所有实现并确定它是否按设计工作,请打开两个不同的终端,并确保您位于项目目录中。 使用以下命令从终端之一运行后端应用程序:
php artisan serve
This will start the application on the default port 8000. Next, to start the frontend application, use npm
as shown here:
这将在默认端口8000上启动应用程序。接下来,要启动前端应用程序,请使用npm
,如下所示:
npm run watch
The preceding command will compile all the Vue.js project and continue running the app in watch mode for changes to any relevant files. Now, navigate to http://localhost:8000, to view the application in your browser:
前面的命令将编译所有Vue.js项目,并继续以监视模式运行该应用程序以更改任何相关文件。 现在,浏览至http:// localhost:8000 ,以在浏览器中查看该应用程序:
Register a user Click on the Register link to register a new user.
注册用户单击“ 注册”链接以注册新用户。
Once the registration process is successful, the user will both be created within your application and also on CometChat. You can log in into your CometChat dashboard and click on the Users tab to view the newly created users. Login and start a chat session Immediately after registration, you will be redirected to the Login page. Input the appropriate credential and start a chat session:
一旦注册过程成功,将在您的应用程序内以及CometChat上都创建用户。 您可以登录到CometChat仪表板 ,然后单击“ 用户”选项卡以查看新创建的用户。 登录并开始聊天会话注册后,您将立即重定向到“登录”页面。 输入适当的凭据并开始聊天会话:
In this tutorial, you built a chat application using Laravel and Vue.js. I hope that this gives you a proper understanding of how seamless it is to combine these tools to build an awesome chat experience. As you must have noticed, this application can actually be improved on, and I will leave that for you to enhance.
在本教程中,您使用Laravel和Vue.js构建了一个聊天应用程序。 我希望这能使您正确地理解将这些工具组合在一起以建立令人赞叹的聊天体验的无缝性。 正如您必须已经注意到的那样,实际上可以对该应用程序进行改进,我将其留给您进行增强。
You can also clone the completed app from Github if you want to have a reference.
如果您想获得参考,也可以从Github克隆完成的应用程序。
翻译自: https://scotch.io/tutorials/build-a-chat-app-with-laravel-and-vue
laravel 使用vue