Create a Realtime Chatroom with Laravel, VueJS and Pusher

by Ahmed Khan  May 16, 2017

In today’s article, I am going to create a chatroom using Laravel 5.4, Pusher and VueJs. Since these tools are popular and almost every developer has heard of them, I will skip the theoretical introductions and discussions and go straight to the fun part.

chatroom in laravel and vuejs

Here is a list of components that I will use for this application:

  • Laravel Auth
  • Laravel Mix
  • Laravel Broadcast
  • Pusher for Laravel and VueJS
  • Bootstrap

I recommend that you launch a Cloudways hosted Laravel application for testing the code. If you do not have an account, to sign up for a trial account.

(Note: You may use promo code: PHP15 to get FREE Cloudways hosting credit of $15 on signup.)

Check out the following GIF for server and application launch.

The complete for this application code can be found in the github repo and the live demo can be found here.

Setup User Authentication

The first step is the migration of the existing user table through the following command:

Next, create a basic auth by running the following command:

Create a factory for creating a few users. For this, head to database/factories and open ModelFactory.php. Paste the following code in it.

I will now create several users through the following command that will start up Tinker:

Now. run the following command to create ten users.

Next up is the broadcaster which will broadcast the chat message(s).

Broadcaster For Chat Messages

I will use a database for queues in broadcast. I will first create migration table and then execute the actual migration.

Run the following commands in the terminal for creating the migration tables for queues:

Now run the following command for the migration:

I will now create a Broadcast event for chat message. This event will broadcast the chat message when a user sends a new message to another user.

Run the following command to create the event:

Go to app/Events folder and open ChatMessage.php.

Start by implementing the class with ShouldBroadcast:

Next, create a new public variable $user. Replace the constructor with the following:

And, replace broadcastOn with the following:

   

What I am doing here is broadcasting the user message on ‘chat-message’.$this->user[‘id’] where $this->user[‘id’] is the id of the user to whom the message is being sent.

The final ChatMessage will look like this:

The broadcaster is now ready. I will now setup Pusher, that I will use for broadcasting messages.

Run the following command to install Pusher for PHP:

Now in the .env file, set the values for the following items:

Next, I will create the chat controller.

The Chat Controller

Run the following command in the console:

Now in the controller class, first create a constructor which contains auth middleware. This will let only the authenticated users access the chat.

   

Now create a new function which sends the chat message:

This function is simple. The id is the id of the user to whom the message is being sent. sourceid is the user id who is sending the message and name is the username. message is the chat message. Next, comes the actual broadcasting that returns true.

I will now create a function which will open a chatroom.

Start by creating a new function chatPage():

The final version of ChatController.php will look like this:

The controller is ready for use.

Creating the Chatroom

Go to resources/views and create a new file called chat.blade.php. Paste the following code in it. This code is a mixture of VueJS and blade:

 

Here is how this code works:

I started with adding the list of users to whom you can send messages:

Notice that I have binded getUserId function using VueJS. I will write this function in the app.js file.  

Next, the chat window is binded using VueJS variable chatWindows. It handles all the chat windows that the user is using. It will only be opened when you click a user for sending a message  or some other user send a message to you. Next is the chats variable which handles the chat for that window.

I have also binded chatMessage function.

I will now create routes .Go to the routes folder and open web.php file. Paste the following routes in it.

The frontend is done. I will now create function in VueJS that will handle the chats. .

Write Functions to Handle Chat in VueJS

Before getting started with VueJS. make sure you have npm. Run the following command to install all the packages:

Now run the following command to install VueResource, which I will use for HTTP requests.

Now go to resources/assets/js and open app.js file. Replace the code in it with the following:

Next, run the following command to compile it.

This is how this code works:

First I imported Pusher and vue-resource components:

Next, I added vue-resource to VueJS and initialized Laravel Echo:

I then created VueJS instance in which first I defined the id of the div in which the app would load.

Next, I defined the variables which I will use in this app:

Then, I added Laravel Echo to listen for broadcast events in created() method (which will work when the Vue app is fully created):

   

This function gets the message, and first checks whether an existing chat window is already open for that user. If yes, it sends the message to that chat window. If the chat window does not exists, it will create a new chat window, open it and display the message. Next, I defined ‘X-CSRF-TOKEN’ header for the HTTP requests.

I also created the methods which will handle sending of the message and creation of new chat window for the users.

The application code is finished. I will now test it.  

Testing the Chat Room

Open the login page in three separate browser instances and sign in with any user that you created by the faker.

Now click on any (logged in) user and send a message. In this case, I sent a message to myself from another user. Currently, all browser windows look like this:

I will now send a message to an online user.

Message will be received by that user and a chat window will open.

Now send a message to another user:

And keep sending message to the users.  

Final Words

In this article, I discussed how you could easily setup a realtime private chatroom using Laravel, VueJS and Pusher. This application is very basic and could use several improvements such as saving the messages and filtering users on the basis of their online status.

If you need further help with the code or the application setup, do leave a comment and I will get back to you ASAP.

 

Create Laravel apps without the worry of server management.

Deploy your app on optimized PHP hosting servers for Laravel.

About Ahmed Khan

Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com

Stay Connected:

You Might Also Like...