TUTORIALS

Build a Chat App with Laravel

Umar Elbelel

View GitHub Repo
June 22, 2021

Laravel is a popular PHP framework that is known for its elegant structure and simplicity of connection with new JavaScript frameworks like React.js and Vue.js. It is widely used by developers all over the world and remains one of the most relevant PHP frameworks in the PHP community. In this article, we'll use CometChat's infrastructure to add a chat component to a Laravel application. 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.

This chat session allows registered and authenticated users to engage in a one-on-one conversation. This application will be built using Laravel and Vue.js. Image below illustrates that

Build a Chat App with Laravel
Build a Chat App with Laravel

Prerequisites

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

  • Composer installed globally on your computer.
  • Setting up a CometChat account and creating an App.

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, we will be using the “composer” to create our laravel application. To do so run the code below

composer create-project laravel/laravel CometChat-chatapp-with-laravel

The preceding command will create a fresh Laravel installation in a directory named “CometChat-chatapp-with-laravel” and place it in your development folder or where you ran the command from.

The next thing is to setup our authentication scaffolding, laravel has provided us with an easier way of doing that. run the command below to create your authentication scaffolding, which consists 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 and so on.

after setting up our authentication scaffolding with vue, to effectively use this, run the code below

//install dependencies

npm install

Create CometChat Account

If you haven’t created a CometChat account yet, click here to set up a free CometChat Pro account. Once you are done, create a new CometChat app from your dashboard by clicking on the Add New App button:

Create CometChat Account

Enter the desired name for your application, select a region, technology, and a use case. Once you are done, click on the Add App button to complete the process.

This will automatically spin up a new application for you on CometChat. Depending on the technology selected from the previous step, CometChat will make provision for a quick start guide to facilitate integrating CometChat inside your app or website with ease. You can check it out and go for your preferred option. Once the app is created, you’ll be provided with the app credentials. We’ll specifically be using the app ID, region, and auth key to connect to CometChat’s API.

Modify Migration file

If you open the project in your preferred code editor, you will noticed that a User model and its corresponding migration file has been generated already. We will need to make this conform to the structure of our application. Start by opening the migration file and replace its content with the following:

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

Update protected fillable

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

Next, with the User Model and migration file properly configured, go ahead and 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.

Next, issue the following command to run the migration file and create the appropriate fields in your database:

php artisan migrate

After running the preceding command, we are now set to start implementing the authentication logic for this application.

Backend authentication logic

In this section, we will modify the default authentication logic within Laravel to fit in into our use case. One of the reasons for the process is to return JSON response for the authentication controllers as this will be required to communicate with the frontend application that will be handled by Vue.js.

Start with the RegisterController found in app/Http/Controllers/Auth/RegisterController.php file and replace its content with the following code:

In the file above, we specified the required fields that should be validated during the registration process. And once the user was registered successfully, we returned a JSON response indicating the user’s details.

Update LoginController

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

We modified the logic here to ensure that users can log in by using their username instead of email. Also, once a user is logged in, we returned a User object as a JSON response.

Frontend

As mentioned, Vue.js will be used to handle frontend logics and communication with the javaScript SDK of CometChat. We have already install Vue.js and its dependencies earlier, so we will proceed to install the CometChat javaScript SDK using the following command:

npm install @cometchat-pro/chat --save

Initialize CometChat App

To initialize CometChat, open the resources/js/app.js file and use the following code for it:

Creating views and Cloning the UI Kit for Vue

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

  • Register.vue
  • Login.vue
  • Chat.vue

Lastly, we will leverage on the UI Kit created by CometChat team to set up our 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, open it with a code editor or any file explorer and copy the src folder and paste it in resources/js folder and rename it CometChat-UI. We will reference some components from the file as required.

Before we start implementing our component we will be modifying some files within the CometChat UI Kit, Navigate to  components/messages/CometChatMessageActions

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 our audio file in our CometChat UI Kit to the public folder in our laravel application. For the package to compile our audio, navigate to the webpack.mix.js file and paste the code below

NOTE:

All these changes are made because laravel mix compiles our css and files to our laravel public folder, as such we have to make sure that no file have thesame name. Also laravel mix doesn’t compile audio file which is included in our CometChat UI Kit.

Editing Style in CometChat UI KIT

After setting up our CometChat UI Kit  we will be modifying some files within the CometChat UI Kit, Navigate to  components/messages/CometChatMessageList

open style.js and replace with the code below

Register view

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

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

The authentication flow for this application is to register users within it and also create such user immediately on CometChat using the CometChat.createUser method. Here, we created the registerAppUser() to register users within our application. And once that is successful, we used the createUserOnCometChat() method to create the user on CometChat with the same unique username. And then we redirect the user to our login page

Login View

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

We created the input fields for username and password. Next paste the following  <script></script> that contains the logic to login a user:

Once a user can log in successfully into our application, we then use CometChat.login() method which accept the AUTH_KEY and the UID (which in this case is our username)  to authenticated the user on CometChat.

Chat view

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

Here, we created a structure that brings together different UI components to represent and build a chat view of our application. Each of the components referenced here is from the UI kit downloaded earlier.

Next, update the <script></script> section with:

First, we imported CometChat SDK and a component from the CometChat-UI folder:

  • CometChatUserListWithMessages: This component take care of everything, from displaying the list of user to displaying there related conversations with the authenticated user. All these are made easier because of the CometChat UI kit.

Import all the created components

So far, we have built the user interface into smaller Vue.js components and before we can make use of them within the appropriate Blade templates, register them as Vue.js components, by adding them to resources/js/app.js as shown here:

Modifying Laravel Blade template

Here, we will make use of all the components created so far within each blade file from Laravel.

Login Blade file

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

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 contents 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:

Test the application

Open different browser and run the command below to start the Laravel application:

php artisan serve

Next, to compile and start the frontend application use the following command:

npm run watch

Now, navigate to http://localhost:8000, 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. You will have a page similar to the one depicted by this image

Log in, select a user and start a chat
Log in, select a user and start a chat

Conclusion

As seen in this tutorial, we started with a non-functional Laravel application, gradually built authentication, programmatically created a user and completed the application by including a chat feature all these by using the CometChat SDK and also CometChat UI kit.

The complete source code can be found here on GitHub. Please feel free to clone it and improve on its existing features.

Related Posts

No items found.
No items found.

Try Us for Free 

For as Long as You Like!