Implementing a chat functionality for a website from scratch takes a lot of time and effort. So it’s wise to utilize platforms such as CometChat to easily build chat functionality in no time.
Before following this tutorial, you first need to make sure you have setup the following. It’s also recommended that you have a bit of experience developing PHP applications:
PHP development environment - this includes PHP, Apache/Nginx, MySQL, and Composer.
CometChat account - you can create a CometChat account here. You’ll be able to use the features in the free account to follow along this tutorial.
Before we proceed, it’s nice to know what we’re actually going to build. We’re going to build an app that allows users to create an account they can use to login in order to participate in the chat for a live online event. The admin creates these events via an admin interface, which we’re also going to build. Here’s what the app is going to look like:
You can find the source code of the app on this GitHub repo.
Setting up CometChat
Once you’re logged in to your CometChat account for the first time, it will prompt you to create a new app. Just put any name you want and save it. That should provide you with an App ID and Auth Key. You can use those later on to connect to the app:
You can also navigate to the API & Auth Keys to view the Rest API key assigned to the app. This is what we’ll use later on to connect to the Rest API so we can create users and chat rooms:
Next, navigate to the Chat Widgets page and create a new chat widget:
Setup the project and database
Create the project by executing the command below on your working directory:
Once that’s done, navigate to the directory it created and install the frontend dependencies:
Next, using your database management tool of choice, create a new database called live_event.
Lastly, rename the .env.example file to .env and supply your database credentials:
Building the app
Now we’re ready to start building the app. Here’s an outline of what we’re going to do:
Update the database migrations
Update the database migrations
We need a database to persist user and event data.
First, update the default users table migration file to include the cometchat_user_id. This corresponds to the ID of the user in CometChat:
Next, create a new migration file for the events table. This is where we’ll store the live events and it corresponds to a group (chat room) in CometChat:
php artisan make:migration create_events_table
Add the following inside the up method:
Let’s implement the registration of users. First, create a new controller:
php artisan make:controller RegisterController
Add the code for serving the page for user registration:
Create the view file at resources/views/register.blade.php and add the following. This allows users to create an account using an email and password:
The view above extends the following view:
It also includes the following partial. We use this for displaying an alert message:
We used Bootstrap classes in the above code but Laravel 8 no longer have Bootstrap pre-installed. So we need to install it first before we proceed further. First, execute the following command to provide Laravel with the ability to generate scaffolding for frontend libraries like Bootstrap, React, or Vue:
composer require laravel/ui
Next, install the Bootstrap scaffolding then install Bootstrap:
php artisan ui bootstrap
Now you should be able to include it in your app stylesheet:
At this point, it’s also nice to make sure that your webpack.mix.js file has the following contents. This is to make sure you have all the necessary frontend files:
While developing the app, you can run the following command to instantly recompile the frontend assets everytime you make a change to any of the files specified in the webpack.mix.js file:
npm run watch
Next, add the following in the routes/web.php file:
Once the form is submitted, we first validate the input data using ValidateUser (we’ll create this shortly). Then we make a request to CometChat’s REST API to create a corresponding CometChat user. The API expects us to pass a JSON string containing the user data. By default, only the uid and name is required. Though you can pass other fields as well. Later on, this user will allow us to login to interact with the CometChat chat widget. If the request succeeded, we create the user in the database as well:
In the above code we used a form request class to validate the user input. You can create that with the following command:
php artisan make:request ValidateUser
Open the app/Http/Requests/ValidateUser.php file and replace the authorize and rules method with the following. This validates the user input and redirect them back to the form with the errors:
We also used the User model. That’s already created by default, so all we have to do is update it to include the custom field we added earlier:
Lastly, we fetched a config variable in app/Http/Controllers/RegisterController.php earlier. Add the following to your config/services.php file. This represents the config variables for CometChat:
Update the .env file to include the actual values. You can find these config in the API & Auth Keys and Chat Widgets page of your CometChat account:
At this point, you should now be able to check the output on your browser. Either by executing php artisan serve or via the local domain name you attached to your project.
This app will also have an admin responsible for creating the events. Create a new controller for it:
Open the app/Http/Controllers/EventsManagementController.php file and add the following. This has very similar code with the RegisterController, the only thing that’s different is that we’re creating events instead of users:
Create a resources/views/events/create.blade.php file. An event consists of the title, description, and YouTube URL:
Next, open the routes/web.php file and add the routes for handling event creation:
Go back to the EventsManagementController and add the code for creating an event. This is similar to what we have on the RegisterController. It sends a request to the groups endpoint of the CometChat Rest API to create a group.
This represents the chat room or group chat for the specific event that we’re creating. It requires us to pass the guid, name, and type.
The first two are self-explanatory, they simply give the group a unique ID and a name to describe it. While the type is used to specify the privacy settings for the group. This can be public, private, or password. In this case, we’re using public so everyone can access or join it:
Lastly, create the form request class for validating the event data:
php artisan make:request ValidateEvent
All the fields should be required:
At this point, you should now be able to create events.
Let’s now move on to the user login code. Create a new controller for it:
php artisan make:controller LoginController
Add the following code:
Then for the login view:
Once the user submits the form, we log them in using the credentials they supplied and redirect them to the events page if its valid. Otherwise, we redirect them back to the login page:
By now you should already see the pattern. The next step is to create a form request class for validating the login details. You can check out the GitHub repo if you get stuck.
Lastly, add the login route:
At this point, you should now be able to login with any user you created.
We can now add the code for listing the events:
In the code above, we used the Event model which we haven’t created yet. Generate it using the following command:
php artisan make:model Event
Update it to include the fields we specified in the migration file earlier:
Next, add the code for the events view. This will show the thumbnail, title, description and human-friendly time difference when the event was created. We didn’t ask for the thumbnail when creating events, so instead we use the YouTube video thumbnail:
In the above code, we used a couple of functions: youtubeThumbnail and humanDateDiff. Here’s the code for those. Create an app/helpers.php file and add the following:
To make the functions accessible anywhere, we need to autoload the file. Open your composer.json file and add the following:
Once that’s done, execute the following command so that the new file can be autoloaded by composer:
Lastly, add the events route. We’re also adding the individual event page route so we don’t have to add it later:
At this point, you should now be able to list events on your browser. Provided you have created an event, and a new user and logged in with it.
Now we’re ready to add the code for the main page of this app, the event page. As you have seen from the route earlier, this accepts an ID which we can use for querying the database. But instead of the event ID, we’re using the ID of the CometChat group instead. That way, users can’t easily guess the ID since it’s a random string:
Next, add the code for the event view:
That’s a lot of code so let’s break it down. First, we include FontAwesome and the custom styles for the page:
Next, we include the CometChat widget script. This allows us to use the CometChat widget:
Let’s break down the above code a bit. First, we initialize the chat widget using the app credentials we declared earlier in the resources/views/event.blade.php file:
Once that succeeds, we login the CometChat user. This is the corresponding CometChat ID of the currently logged in user:
Then we launch the widget. This requires us to pass the widget ID, target element, and the group ID for the specific chat. A chat can either be one on one (user) or group chat (group):
We’re not quite done yet. The CometChat widget comes with a default styling so we have to update it a bit so it looks a bit closer to the YouTube chat widget styling. You can do that by going to the chat widgets page. Click on the chat widget you created earlier, then click on the Customize tab. Scroll to the bottom and click on Custom CSS:
Paste the following styles inside the text field. For the most part, this simply hides all the elements we don’t need and re-aligns the one’s we need to make it look like the YouTube chat widget:
Lastly, add the event.css file and resources/js/chat-widget.js to your webpack.mix.js file:
Then compile the frontend assets:
npm run production
At this point, the app is now complete. You should now be able to open up multiple browsers and test out the chat functionality. Just register an account, login and then select an event to view.
In this tutorial, you learned how to build a live event site using Laravel and CometChat. Specifically, you learned how to use CometChat’s Rest API to create new users and groups. You also learned how to easily implement chat functionality using CometChat’s chat widget.
You can view the source code of this project in this GitHub repo.