How to build a Laravel chat application using Vue.js

How to build a Laravel chat application using Vue.js

In this post, I will be showing you how to build a Laravel chat application. I will be using Vue.js as my JavaScript framework, although you can use the JavaScript framework of your choice or even jQuery and vanilla JavaScript.

In this post, I will be showing you how to build a Laravel chat application. I will be using Vue.js as my JavaScript framework, although you can use the JavaScript framework of your choice or even jQuery and vanilla JavaScript.

Laravel makes it easy to build modern applications with realtime interactions by providing an event broadcasting system which allows developers to share the same event names between the server-side code and the client-side JavaScript application.

Before we start, let's take a quick look at what we'll be building.

The code of the completed demo is available on GitHub.

Setting Up Laravel

We'll start by creating a new Laravel project. While there are different ways of creating a new Laravel chat application project, I prefer using the Laravel installer. Open your terminal and run the code below:

laravel new laravel-chat

This will create a laravel-chat project within the directory where you ran the command above.

Before we start using Laravel event broadcasting, we first need to register the App\Providers\BroadcastServiceProvider. Open config/app.php and uncomment the following line in the providers array.

// App\Providers\BroadcastServiceProvider

We need to tell Laravel that we are using the Pusher driver in the .env file:

// .env

BROADCAST_DRIVER=pusher

Though Laravel supports Pusher out of the box, we still need to install the Pusher PHP SDK. We can do this using composer:

composer require pusher/pusher-php-server

Once the installation is done, we need to configure our Pusher app credentials in config/broadcasting.php. To get our Pusher app credential, we need to have a Pusher account.

Setting Up Pusher

If you don't have one already, create a free Pusher account at https://pusher.com/signup then login to your dashboard and create an app.

Now, let's fill in our Pusher app credentials. If you open the config/broadcasting.php, you'll notice that Laravel is pulling some of Pusher credential from the .env file:

// Don't add your credentials here!
// config/broadcasting.php

'pusher' => [
  'driver' => 'pusher',
  'key' => env('PUSHER_APP_KEY'),
  'secret' => env('PUSHER_APP_SECRET'),
  'app_id' => env('PUSHER_APP_ID'),
  'options' => [],
],

We need to modify the source a little bit here to get this to work. Modify the source so that it looks like this:

  'pusher' => [
      'driver' => 'pusher',
      'key' => env('PUSHER_APP_KEY'),
      'secret' => env('PUSHER_APP_SECRET'),
      'app_id' => env('PUSHER_APP_ID'),
      'options' => [
          'cluster' => env('PUSHER_CLUSTER'),
          'encrypted' => true,
      ],
  ],

Then let's update the .env file to contain our Pusher app credentials (noting the added cluster credential, this won't be in your .env file as Laravel has not added this functionality yet:

// .env

PUSHER_APP_ID=xxxxxx
PUSHER_APP_KEY=xxxxxxxxxxxxxxxxxxxx
PUSHER_APP_SECRET=xxxxxxxxxxxxxxxxxxxx
PUSHER_CLUSTER=xx

Remember to replace the xs with your Pusher app credentials. You can find your app credentials under the Keys section on the Overview tab.

Now that we've set up the back-end of our project, let's move on to setting up the front-end. Laravel provides some front-end frameworks and libraries, including - Bootstrap, Vuejs and Axios which we'll be using in this tutorial.

We'll also be making use of Laravel Mix, which is a wrapper around Webpack that will help us compile our CSS and JavaScript.

But first, we need to install these dependencies through NPM:

npm install

To subscribe and listen to events, Laravel provides Laravel Echo, which is a JavaScript librarythat makes it painless to subscribe to channels and listen for events broadcast by Laravel. We'll need to install it along with the Pusher JavaScript library:

npm install --save laravel-echo pusher-js

Once installed, we need to tell Laravel Echo to use Pusher. At the bottom of the resources/assets/js/bootstrap.js file, Laravel have stubbed Echo integration though it is commented out. Simply uncomment the Laravel Echo section and update the details with:

// resources/assets/js/bootstrap.js

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxxxxxxx',
    cluster: 'eu',
    encrypted: true
});

Remember to replace the xs with your Pusher app key. Also use the same cluster that you specified earlier in config/broadcasting.php.

Now that we are done with setting up Laravel and Pusher and other dependencies, it time to start building our chat application.

Authenticating Users

Our chat app will require users to be logged in before they can begin to chat. So, we need an authentication system, which with Laravel is as simple as running an artisan command in the terminal:

php artisan make:auth

This will create the necessary routes, views and controllers needed for an authentication system.

Before we go on to create users, we need to run the users migration that comes with a fresh installation of Laravel. But to do this, we first need to setup our database. Open the .env file and enter your database details:

// .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-chat
DB_USERNAME=root
DB_PASSWORD=root

There's a bug in Laravel 5.4 if you're running a version of MySQL older than 5.7.7 or MariaDB older than 10.2.2. More info here. This can be fixed by replacing the boot() of app/Providers/AppServiceProvider.php with:

// app/Providers/AppServiceProvider.php // remember to use Illuminate\Support\Facades\Schema; /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); }

Message Model and Migration

Create a Message model along with the migration file by running the command:

php artisan make:model Message -m

Open the Message model and add the code below to it:

// app/Message.php

/**
 * Fields that are mass assignable
 *
 * @var array
 */
protected $fillable = ['message'];

Within the databases/migrations directory, open the messages table migration that was created when we ran the command above and update the up method with:

Schema::create('messages', function (Blueprint $table) {
  $table->increments('id');
  $table->integer('user_id')->unsigned();
  $table->text('message');
  $table->timestamps();
});

The message will have five columns: an auto increment id, user_id, message, created_at and updated_at. The user_id column will hold the ID of the user that sent a message and the message column will hold the actual message that was sent. Run the migration:

php artisan migrate

User To Message Relationship

We need to setup the relationship between a user and a message. A user can send many messages while a particular message was sent by a user. So, the relationship between the user and message is a one to many relationship. To define this relationship, add the code below to User model:

// app/User.php

/**
 * A user can have many messages
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function messages()
{
  return $this->hasMany(Message::class);
}

Next, we need to define the inverse relationship by adding the code below to Message model:

// app/Message.php

/**
 * A message belong to a user
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function user()
{
  return $this->belongsTo(User::class);
}
Defining App Routes

Let's create the routes our chat app will need. Open routes/web.php and replace the routes with the code below to define three simple routes:

// routes/web.php

Auth::routes();

Route::get('/', '[email protected]');
Route::get('messages', '[email protected]');
Route::post('messages', '[email protected]');

The homepage will display chat messages and an input field to type new messages. A GET messages route will fetch all chat messages and a POST messages route will be used for sending new messages.

NOTE: Since we have removed the /home route, you might want to update the redirectTo property of both app/Http/Controllers/Auth/LoginController.php and app/Http/Controllers/Auth/RegisterController.php to:

protected $redirectTo = '/';

ChatsController

Now let's create the controller which will handle the logic of our chat app. Create a ChatsController with the command below:

php artisan make:controller ChatsController

Open the new create app/Http/Controllers/ChatsController.php file and add the following code to it:

// app/Http/Controllers/ChatsController.php

use App\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

public function __construct()
{
  $this->middleware('auth');
}

/**
 * Show chats
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
  return view('chat');
}

/**
 * Fetch all messages
 *
 * @return Message
 */
public function fetchMessages()
{
  return Message::with('user')->get();
}

/**
 * Persist message to database
 *
 * @param  Request $request
 * @return Response
 */
public function sendMessage(Request $request)
{
  $user = Auth::user();

  $message = $user->messages()->create([
    'message' => $request->input('message')
  ]);

  return ['status' => 'Message Sent!'];
}

Using the auth middleware in ChatsController's __contruct() indicates that all the methods with the controller will only be accessible to authorized users. Then the index() will simply return a view file which we will create shortly. The fetchMessages() return a JSON of all messages along the their users. Lastly, the sendMessage() will persist the message into the database and return a status message.

Creating The Chat App View

For the chat app view, we'll be making use of Bootsnipp chat snippet with some few modifications.

Create a new resources/views/chat.blade.php file and paste into it:



@extends('layouts.app')

@section('content')


    
        
            
                Chats


                
                    
                
                
                    <chat-form
                        v-on:messagesent="addMessage"
                        :user="{{ Auth::user() }}"
                    >
                
            
        
    

@endsection

Notice we have some custom tags with the chat view, these are Vue components which we'll create soon. The chat-messages component will display our chat messages and the chat-form will provide an input field and a button to send the messages.

Before we go to create our Vue component, let's add the styles for the chat view. Open resources/views/layouts/app.blade.php (which was created when we ran make:auth) and add the code below just after the styles link:




Looking at the resources/assets/js/bootstrap.js, you will notice that Laravel has set up some of the front-end dependencies (jQuery, Bootstrap, Lodash, Vue, Axios, Echo) that are included out of the box. We can start using Vue without any further setup.

Create a new ChatMessages.vue file within resources/assets/js/components and paste the code below into it:


// resources/assets/js/components/ChatMessages.vue


    
        
            
                
                    
                        {{ message.user.name }}
                    
                
                
                    {{ message.message }}
                
            
        
    



The ChatForm component displays an input field and a send button. It accepts the authenticated user as props. It also contains newMessage data which is bound to the input field. When the send button is clicked or the enter key is pressed on the input field, a sendMessage() is called. The sendMessage() simply triggers a messagesent event which passes along the message that was sent by the user to the root Vue instance (which will handle the actual sending of the message) and finally clear the input filed.

Next, we need to register our component in the root Vue instance. Open the resources/assets/js/app.js and update with code below:

/ resources/assets/js/app.js

require('./bootstrap');

Vue.component('chat-messages', require('./components/ChatMessages.vue'));
Vue.component('chat-form', require('./components/ChatForm.vue'));

const app = new Vue({
    el: '#app',

    data: {
        messages: []
    },

    created() {
        this.fetchMessages();
    },

    methods: {
        fetchMessages() {
            axios.get('/messages').then(response => {
                this.messages = response.data;
            });
        },

        addMessage(message) {
            this.messages.push(message);

            axios.post('/messages', message).then(response => {
              console.log(response.data);
            });
        }
    }
});

Once the Vue instance is created, using Axios, we make a GET request to the messages route and fetch all the messages then pass it to the messages array that will be displayed on the chat view. The addMessage() receives the message that was emitted from the ChatForm component, pushes it to the messages array and makes a POST request to the messages route with the message.

Broadcasting Message Sent Event

To add the realtime interactions to our chat app, we need to broadcast some kind of events based on some activities. In our case, we'll fire a MessageSent when a user sends a message. First, we need to create an event, we'll call it MessageSent:

php artisan make:event MessageSent

This will create a new MessageSent event class within the app/Events directory. This class must implement the ShouldBroadcast interface. The class should look like:

// app/Events/MessageSent.php

use App\User;
use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * User that sent the message
     *
     * @var User
     */
    public $user;

    /**
     * Message details
     *
     * @var Message
     */
    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user, Message $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat');
    }
}

We defined two public properties that will be the data that will be passed along to the channel we are broadcasting to.

NOTE: These properties must be public for it to be passed along to the channel.

Since our chat app is an authenticated-only app, we create a private channel called Chat, which only authenticated users will be able to connect to. Using the PrivateChannel class, Laravel is smart enough to know that we are creating a private channel, so don't prefix the channel name with private- (as specified by Pusher), Laravel will add the private- prefix under the hood.

Next, we need to update the sendMessage() of ChatsController to broadcast the MessageSent event:

// app/Http/Controllers/ChatsController.php

//remember to use
use App\Events\MessageSent;

/**
 * Persist message to database
 *
 * @param  Request $request
 * @return Response
 */
public function sendMessage(Request $request)
{
  $user = Auth::user();

  $message = $user->messages()->create([
    'message' => $request->input('message')
  ]);

  broadcast(new MessageSent($user, $message))->toOthers();

  return ['status' => 'Message Sent!'];
}

Since we created a private channel, only authenticated users will be able to listen on the chat channel. So, we need a way to authorize that the currently authenticated user can actually listen on the channel. This can be done by in the routes/channels.php file:

// routes/channels.php

Broadcast::channel('chat', function ($user) {
  return Auth::check();
});

We pass to the channel(), the name of our channel and a callback function that will either return true or false depending on whether the current user is authenticated.

Now when a message is sent, the MessageSent event will be broadcast to Pusher. We are using the toOthers() which allows us to exclude the current user from the broadcast's recipients.

Listening For Message Sent Event

Once the MessageSent event is broadcast, we need to listen for this event so we can update the chat messages with the newly sent message. We can do so by adding the code snippet below to created() of resources/assets/js/app.js just after this.fetchMessages():

// resources/assets/js/app.js

Echo.private('chat')
  .listen('MessageSent', (e) => {
    this.messages.push({
      message: e.message.message,
      user: e.user
    });
  });

We subscribe to the chat channel using Echo's private() since the channel is a private channel. Once subscribed, we listen for the MessageSent and based on this, update the chat messages array with the newly sent message.

Before testing out our chat app, we need to compile the JavaScript files using Laravel Mix using:

npm run dev

Now we can start our chat app by running:

php artisan serve

Our chat app is done as we can now send and receive messages in realtime.

Conclusion

You can see how straightforward it is to build a realtime app with Laravel and Pusher. With Pusher, you are not limited to chat apps, you can build any application that requires realtime interactivity.

How to create a live chat app using Laravel and Vue.js

How to create a live chat app using Laravel and Vue.js

In this tutorial, we will be looking at how to build a live chat using Laravel and Vue.js where people can log in and chat with each other. This is a feature we see in applications like YouTube or Facebook during a live event.

Introduction

In this article, we’ll be building an app where users can log in with their usernames and then join a live chat. Here is what our app will look like:

Requirements

To follow along with this article, you need the following:

If you have these requirements we can begin.

Creating our Laravel application

We will start by creating a new Laravel application. By now, you should have the Laravel CLI, so you can just run this command to create a new project:

$ laravel new larachat

This will create a new Laravel application in a larachat folder.

Setting up Pusher Chatkit in the app

Before we go ahead to enable Chatkit in our app, open the Chatkit app, go to the Console tab and create a new user named admin. Create a new room named live-chat with the admin.

Open the room you have just created and note the room ID. Copy it out as you will soon need it.

To enable Chatkit in our app, we will need to add the keys to our app environment. Add these new properties at the bottom of the .env file found in your project directory:

If you don’t have the .env file for some reason, rename the .env.example file to .env and run the command: php artisan key:generate

    # File: .env
    # [...]

    CHATKIT_INSTANCE_LOCATOR="INSTANCE_LOCATOR_HERE"
    CHATKIT_SECRET_KEY="SECRET_KEY_HERE"
    CHATKIT_GENERAL_ROOM_ID="GENERAL_ROOM_ID"

    MIX_APP_URL="${APP_URL}"
    MIX_CHATKIT_INSTANCE_LOCATOR="${CHATKIT_INSTANCE_LOCATOR}"

You need to replace the placeholder values with the credentials from your Chatkit app. The CHATKIT_INSTANCE_LOCATOR and CHATKIT_SECRET_KEY can be gotten from the Credentials tab of the Chatkit instance. Replace CHATKIT_GENERAL_ROOM_ID with the room ID you copied out earlier. MIX_APP_URL and MIX_CHATKIT_INSTANCE_LOCATOR references the APP_URL and CHATKIT_INSTANCE_LOCATOR respectively.

Still in the .env file, update the APP_URL like so:

    APP_URL=http://localhost:8000

To enable our application can use the environment credentials we added earlier, open the config/services.php file and in there add the snippet below to the array of third-party services:

    // File: config/services.php
    'chatkit' => [
        'secret' => env('CHATKIT_SECRET_KEY'),
        'locator' => env('CHATKIT_INSTANCE_LOCATOR'),
    ],

Next we will need to do is install the Chatkit PHP SDK. Run this command in the root directory of your project to install the Chatkit package:

$ composer require pusher/pusher-chatkit-server

Next, open app/providers/AppServiceProvider.php and add the following code inside the register method:

    // File: app/providers/AppServiceProvider.php
    $this->app->bind('ChatKit', function() {
        return new \Chatkit\Chatkit([
            'instance_locator' => config('services.chatkit.locator'),
            'key' => config('services.chatkit.secret'),
        ]);
    });

The above snippet will bind the Chatkit service within the register method into Laravel’s IoC container. We can now resolve it from anywhere within our app and it will return an instance of the configured Chatkit class.

Building the application logic

Now we have our Laravel application configured and Chatkit SDK setup, let’s write the core functionality of our chat app.

First, we will create and update some controllers. Still in your root directory, run this command to create a new controller:

$ php artisan make:controller ChatkitController

Open the app/Http/Controllers/ChatkitController.php file and replace the contents with this snippet:

    <?php
    // File: app/Http/Controllers/ChatkitController.php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    class ChatkitController extends Controller
    {
        private $chatkit;
        private $roomId;

        public function __construct()
        {
            $this->chatkit = app('ChatKit');
            $this->roomId = env('CHATKIT_GENERAL_ROOM_ID');
        }

        /**
         * Show the welcome page.
         *
         * @return \Illuminate\Contracts\Support\Renderable
         */
        public function index(Request $request)
        {
            $userId = $request->session()->get('chatkit_id')[0];

            if (!is_null($userId)) {
                // Redirect user to Chat Page
                return redirect(route('chat'));
            }

            return view('welcome');
        }

        /**
         * The user joins chat room.
         *
         * @param  \Illuminate\Http\Request $request
         * @return mixed
         */
        public function join(Request $request)
        {
            $chatkit_id = strtolower(str_random(5));

            // Create User account on Chatkit
            $this->chatkit->createUser([
                'id' =>  $chatkit_id,
                'name' => $request->username,
            ]);

            $this->chatkit->addUsersToRoom([
                'room_id' => $this->roomId,
                'user_ids' => [$chatkit_id],
            ]);

            // Add User details to session
            $request->session()->push('chatkit_id', $chatkit_id);

            // Redirect user to Chat Page
            return redirect(route('chat'));
        }

        /**
         * Show the application chat room.
         *
         * @return \Illuminate\Contracts\Support\Renderable
         */
        public function chat(Request $request)
        {
            $roomId = $this->roomId;

            $userId = $request->session()->get('chatkit_id')[0];

            if (is_null($userId)) {
                $request->session()->flash('status', 'Join to access chat room!');
                return redirect(url('/'));
            }

            // Get messages via Chatkit
            $fetchMessages = $this->chatkit->getRoomMessages([
                'room_id' => $roomId,
                'direction' => 'newer',
                'limit' => 100
            ]);

            $messages = collect($fetchMessages['body'])->map(function ($message) {
                return [
                    'id' => $message['id'],
                    'senderId' => $message['user_id'],
                    'text' => $message['text'],
                    'timestamp' => $message['created_at']
                ];
            });

            return view('chat')->with(compact('messages', 'roomId', 'userId'));
        }

        /**
         * Receives a client request and provides a new token.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return mixed
         */
        public function authenticate(Request $request)
        {
            $response = $this->chatkit->authenticate([
                'user_id' => $request->user_id,
            ]);

            return response()
                ->json(
                    $response['body'],
                    $response['status']
                );
        }

         /**
         * Send user message.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return mixed
         */
        public function sendMessage(Request $request)
        {
            $message = $this->chatkit->sendSimpleMessage([
                'sender_id' => $request->user,
                'room_id' => $this->roomId,
                'text' => $request->message
            ]);

            return response($message);
        }

        /**
         * Get all users.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return mixed
         */
        public function getUsers()
        {
            $users = $this->chatkit->getUsers();

            return response($users);
        }

        /**
         * Get all users.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return mixed
         */
        public function logout(Request $request)
        {
            $request->session()->flush();

            return redirect(url('/'));
        }
    }

In the ChatkitController above we have several methods, namely: index, join, chat, authenticate, sendMessage, getUsers and logout.

The index method returns the welcome page if a user ID doesn’t exist in the current session else it redirects to the chat page.

The join method uses the resolved Chatkit SDK instance, creates a new user on Chatkit and add the user to the live-chat room and then save the users Chatkit ID in the current session before redirecting the user to the chat page.

The chat method handles the chat page when loaded on the browser. Inside it, we get the current user Chatkit ID from the session. If a Chatkit ID is not found, we return the user to the welcome page. The Chatkit ID, room ID, and chat room messages properties are then passed to the chat page view.

The authenticate method will act as a token provider server that receives the client's request and returns a valid JWT to your Chatkit client.

In the sendMessage method, we use the SDK’s sendSimpleMessage method, which accepts the sender_id, room_id and text to send a message to the chat room. The getUsers method returns all the users created on our Chatkit instance. Our logout method flushes the current session and redirects to the welcome page.

Next, we will update the web routes. Open routes/web.php and paste the code below to override the default :

    // File: routes/web.php
    Route::get('/', '[email protected]');
    Route::post('/', '[email protected]');
    Route::get('chat', '[email protected]')->name('chat');
    Route::post('logout', '[email protected]')->name('logout');

Open routes/api.php and add the code below in the file:

    // File: routes/api.php
    Route::post('authenticate','[email protected]');
    Route::get('users', '[email protected]');
    Route::post('message','[email protected]');

The newly added routes will provide endpoints to authenticate a client request, show a chat and send a message.

Building the application frontend

First, we will update the welcome page of the app. Open a resources/views/welcome.blade.php file and paste the code below to update the file:

    
    
    getLocale()) }}">
    
        
        
        Live Chat
        
        
        
        
        
        
        
    
    
        
            
                
                    Join Live Chat
                
                @if(Session::has('status'))
                    
                        {{ Session::get('status') }}
                    
                @endif
                
                    
                        @csrf
                        
                            <input type="text" name="username" class="form-control" 
                              placeholder="Enter your username">
                            
                                
                                  Join
                                
                            
                        
                    
                
            
        
    
    

The welcome.blade.php view contains a Join Live Chat title and a simple form that submits the entered username in the input field to join the live chat room.

Next, we will build the chat page to read and send messages. A chatbox component will be created using Vue.js to handle the chat feature.

Open a terminal tab in your project directory and run the command below:

$ npm install

This command installs the required development dependencies in the package.json file. Next, we need to install Chatkit. Run this command to install it:

$ npm install moment @pusher/chatkit-client --save-dev

Now create a ChatBoxComponent.vue file in the resources/js/components/ directory and paste the code snippet below inside the file.

    
    
      
        
            
                * ({{ formatTime(message.timestamp) }}) * : **{{ findSender(message.senderId).name }}**
                {{ message.text }}
            
        
        
* * *

        
            
            
              Send
            
        
      
    

    
    

The ChatBoxComponent.vue single file component is divided into three sections:

  • template tag contains our HTML syntax for the chat box providing the information to be shown.
  • script tag holds the logic that keeps data and methods. It also performs various operations like authentication, sending and receiving messages.
  • style tag provides the simplest option to add CSS to a Vue.js component.

The script tag keeps the logic of our Vue component. Inside this tag, first, we imported the libraries we will make use of. The export default block exports an object literal as our component’s view model and is responsible for the behavior of our component. This block houses other sections.

The props section helps us to pass custom data to the component from its instances. The data section is used to set up the component state. Every property you define in data becomes reactive meaning that if there is a change, it will be reflected in the view.

The method section holds the methods just as the name implies. In our component, we have six methods for various actions.

  • connectToChatkit method handles the connection to Chatkit from the client (browser) interface. It defines a TokenProvider and then the ChatManager is created with the token provider, allowing the client to connect to the Chatkit servers. On a successful connection, the currentUser data state is updated and the subscribeToRoom method is called.
  • subscribeToRoom method handles the connection to a particular room and is able to hook in some actions to respond to certain events like when a new message is sent, a user joins the room or leaves the room.
  • getUser method fetches all users on the Chatkit instance and updates the users data state with the response body gotten.
  • sendMessage method gets data from the input field and makes a post request to send the message.
  • findSender method accepts a senderId parameter and uses this to find a user on the this.users data.
  • formatTime method using the imported moment library returns a human readable time.

The created section is one of the used life cycle hooks used for initialization. In our case, we called the connectToChatkit and getUsers method there.

Next, open resources/js/app.js and add the Vue instance like so:

    // resources/js/app.js
    Vue.component('chatbox', require('./components/ChatBoxComponent.vue').default); 

The above code line registers the ChatBoxComponent.vue using chatbox as its basename. Now, go back to the terminal and run the command below:

$ npm run dev

This command will run a development build process using webpack to compile all resources/js files into the public/js/app.js file.

The command npm run prod is used in the case you want to it in a production environment

Next, create a resources/views/chat.blade.php file and paste the code below:

    
    
    getLocale()) }}">
    
        
        
        
        
        Live Chat
        
        
        
        
        
        
        
    
    
        
            
                <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault();
                document.getElementById('logout-form').submit();">
                    Leave Chat Room
                
                
                    @csrf
                
            
            
                
                    
                        
                             Live Chat Room 

                             
                        
                    
                
            
        
    
    

Inside the chat.blade.php, we added the chatbox tag that renders our ChatBoxComponent we created earlier and above it, we have Leave Chat Room link that logs the user out.

Finally, to test our app run the command below to serve the application:

$ php artisan serve

Now open http://localhost:8000 on two separate browser windows. Register two different accounts and try chatting between the two users. You should have results similar to this:

Conclusion

In this tutorial, we have seen how to add a live chatting experience to our app. The application was created using Laravel and Vue.js. The Chatkit API is very extensible and provides features not covered in this tutorial. You can leverage this knowledge to work with other features Chatkit provides in a Laravel app.

The source code is available on GitHub.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.