Build a Chat App with Laravel

In this tutorial, we will take advantage of the infrastructure put in place by CometChat to implement a chat feature for a Laravel application in no time. This will be a step by step guide that allows you to build authentication and authorization for each user before an access can be granted for participation in a chat session.

Umar Elbelel • Aug 10, 2020

Two users log in to the completed application and start a conversation

The completed application

Laravel is a popular PHP framework that is known for its elegant structure and simplicity when working with JavaScript frameworks like React.js and Vue.js. It is widely used by developers all over the world and remains one of the most popular frameworks in the PHP community. In this tutorial, you'll use CometChat's infrastructure to add a chat component to a Laravel application. This step by step guide will show you how to add authentication and authorization for each user before they can access the chat session itself.

You will use Laravel and Vue.js to build a chat service that allows users to engage in one-on-one conversations with each other.

The complete source code can be found on GitHub.

What You Will Need

Any existing knowledge of building web applications with Laravel will help you get the best out of this tutorial. Also, ensure that you have:

Creating a new Laravel Chat App

To create a laravel application, we have two methods i.e using "composer” or “laravel installer”. For this tutorial, you use composer to create your laravel application.

To create a new project run the command:

‍_composer create-project laravel/laravel CometChat-chatapp-with-laravel_

This will create a fresh Laravel installation in a directory named CometChat-chatapp-with-laravel

The next thing to do is to set up the authentication scaffolding. Laravel provides an easy way to do this. Run the commands below to create your authentication scaffolding, consisting of the User model and migration file, Authentication controller, blade views for registration and login, main application layout file, and a default structure for the Vue.js component.

Then, run npm install

To install CometChat’s JavaScript SDK using the following command:

npm install @cometchat-pro/chat --save

Vue.js will be used to handle the frontend code and communication with the CometChat SDK.

Create a CometChat Pro App

You will need to create a new App:

Provide a name for your app and select the region you want to use.

build-a-chat-app-with-laravel-img-1

Find Your App’s Credentials

Once your App has been created you can find your APP ID and Auth Key on the ‘Quick Start’ page.

build-a-chat-app-with-laravel-img-2

Modify the Migration File

If you open the project in your preferred code editor, you will notice that a User model and its corresponding migration file has been generated already. We will need to modify this to conform to the structure of our application.

Open the migration file and replace its content with the following:

Here, we modified the content of this file to create username and password fields in the database.

Next, open the User model in app/User.php and modify the $fillable property:

Now that you have modified the User Model and migration file you can create a database for your application and update the .env file with its details:

Ensure that you replace the YOUR_DB_NAME, YOUR_DB_USERNAME and YOUR_DB_PASSWORD placeholders with your credentials.

In order to run the migration file and create the appropriate fields in your database, run the command:

php artisan migrate

Backend Authentication Logic

You need to modify the default authentication logic provided by Laravel to return a JSON response to the authentication controllers which will be required to communicate with the frontend application that will be handled by Vue.js.

Open RegisterController found in app/Http/Controllers/Auth/RegisterController.php and replace the contents with the following code:

This specifies the required fields that should be validated during the registration process. Once the user is registered successfully, a JSON object is returned with the user’s details.

Update the Login Controller

Next, open the app/Http/Controllers/Auth/LoginController.php file and use the following code for it:

Here you modified the logic to ensure that users can log in using their username instead of email. Once a user is logged in, you return a User object in the response as a JSON object.

Frontend

As mentioned, Vue.js will be used to handle frontend logics and communication with the javaScript SDK of CometChat. You have already install Vue.js and it's dependencies earlier.

Initialize CometChat App

To initialize CometChat, open resources/js/app.js and add the following code:

Creating views and Cloning the UI Kit for Vue

In this section, you will create a login, register, and chat view for users. To begin, create a folder named views within the resources/js folder and add the following files:

  • Register.vue

  • Login.vue

  • Chat.vue

For this tutorial you will leverage the UI Kit created by the CometChat team to set up the chat view. This comes with the benefit of an appealing user interface and a proper structure for chat applications. To use the kit, clone or download it from this repository using the following command:

git clone https://github.com/cometchat-pro/vue-chat-ui-kit.git

Once you are done, copy the src folder and paste it into the resources/js folder and rename it CometChat-UI. You will reference components from the file as required.

Before you can start implementing your component you need to modify some files within the CometChat UI Kit, Navigate to components/messages/CometChatMessageActions and open CometChatMessageActions.vue and change the code below.

Once this is done, run the command below to install file-loader:

npm install file-loader --save

file-loader helps us mix the audio file in the CometChat UI Kit into the public folder of our Laravel application. For the package to compile the audio, navigate to the webpack.mix.js file and paste the code below

These changes are required because Laravel mix compiles our css and files to the Laravel public folder, as such you have to make sure that no files have the same name. Laravel mix also needs to know how to compile the audio file which is included in our CometChat UI Kit.

Editing Style in the CometChat UI KIT

After setting up the CometChat UI Kit you will need to modify some of the files. Open components/messages/CometChatMessageList/style.js and replace the contents with the code below:

Register view

Open Register.vue and paste the following content in it:

Next, paste the following code immediately after the template section:

When a user registers to use the application we need to store their account information in the database and register an account in the CometChat App to enable them to send messages through the CometChat service

In the code above you created the registerAppUser() function to register users within the application. Once that is successful, the createUserOnCometChat() method creates the user on CometChat with the same unique username before redirecting the user to the login page.

Login View

Open Login.vue and paste the code below in it:

This creates the input fields for username and password.

Next add the following <script> element which contains the logic to login a user:

Once the user has authenticated successfully with the application, the CometChat.login() function is used to authenticate them with the CometShat service. This method requires the AUTH_KEY for your app and the UID (which in this case is our username) for the user on CometChat.

Chat view

To create the chat view, start by pasting the following code in resources/views/Chat.vue:

This creates a structure that brings together different UI components to represent and build a chat view for the application. Each of the components referenced here is from the UI kit downloaded earlier.

Next, update the <script> element:

This imports the CometChat SDK and a component from the CometChat-UI folder:

The CometChatUserListWithMessages component takes care of everything, from displaying the list of users to displaying their related conversations.

Import all the Created Components

So far, you have built the user interface using Vue.js components. However, before you can make use of them within the appropriate Blade templates they need to be registered by adding them to resources/js/app.js as shown below:

Modifying the Laravel Blade Templates

Now you need to modify Laravel's Blade templates to use the components you have just created.

Login Blade file

Start with the login.blade.php file in resources/views/auth folder and paste the following content:

Register

Use the content below for resources/views/auth/register.blade.php:

Home

Finally, render the chat component within resources/views/home.blade.php

Welcome page

Change the content rendered on the homepage by replacing the content of resources/views/welcome.blade.php file with the following:

Update Stylesheet

Replace the content of resources/sass/app.scss file with:

Layout file

To update the Layout file. Replace the content of Layout.blade with the following:

Testing the application

In order to test that you application is working properly, run the command below to start the Laravel application:

php artisan serve

And then compile and start the frontend application use the command:

npm run watch

Now, if you navigate to http://localhost:8000, you will be able to view the application in your browser.

Register Users

Go ahead and register as a new user. You can create two separate accounts for testing purposes:

Register Users

Log in, Select a User and Start a Chat

Now, login and select a user to chat with.

Log in, select a user and start a chat

If you have the application open in two different browsers you should be able to send messages between the two logged in users.

Conclusion

In this tutorial, you started with a non-functional Laravel application, gradually built authentication, programmatically created a user and completed the application by including a chat feature using the CometChat SDK and CometChat UI kit.

Umar Elbelel

CometChat

-

Try out CometChat in action

Experience CometChat's messaging with this interactive demo built with CometChat's UI kits and SDKs.