How To Build A Realtime Chat App With Laravel 5.4 And VueJs

Webskitters
Aug 9, 2017 · 5 min read

Laravel is a very upcoming field in the modern world. This platform has helped one develop various aspects of platform in an effortless way. The use of Laravel Echo has also become very common. Laravel Echo is a Javascript library which makes it painless to subscribe to various channels and listen for event broadcast by Laravel.

There is also the availability of pusher message service where one can create an account with the own messenger. With the use of Laravel 5.3 for blade files as well as Laravel Echo’s frontend library with vue-resource, the whole process will get very easy running fast.

Right at end, one should be able to open two browsers and see accordingly if the chat is working.

The dependencies which one has to install

The whole starts with installing these packages for getting up and then running with Laravel Echo/Broadcasting events.

One may install Echo via NPM package manager. Take the example, where we can install the pusher-js package; one will be using the Pusher broadcaster:

One can run npm install- save laravel-echo pusher-js in the terminal.

Now if one is broadcasting the events over Pusher, then one should install the Pusher PHP SDK with the use of Composer package manager:

composer require pusher/pusher-php-server

Now when one have all the dependencies easily installed, it will be time for setting up a pusher.com account. When one have accordingly created an account and then created an App then one should see certain App keys under the tab App keys.

Just copy that key to your entire .env file like this.

PUSHER_APP_ID=23222  
PUSHER_KEY=ffssfb166f4976941e627c5
PUSHER_SECRET=2o2323ojfw

And remember to see the broadcast driver so that Laravel will know what driver will want to use.

BROADCAST_DRIVER=pusher

In the config/broadcasting.php file, it is good idea for adding some options to pusher connection like this

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

Now we should try to create event to see if one can push some messages right into Pusher account.

Just go to the terminal and then type php artisan making the event MessagePosted.

find the class in the app/events/ChatMessageWas Received.php making it implement the ShouldBroadcast. So like this

class ChatMessageWasReceived implements ShouldBroadcast  
{

Now we want to create an appropriate chat message, we type PHP artisan make:model ChatMessage –migration. This is can create a model and a migration for us and start this or add own rows.

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

Make sure to add $fillable to the model.

class ChatMessage extends Model  
{
public $fillable = ['user_id', 'message'];
}

Now try injecting a user and the messages right to the event

class ChatMessageWasReceived implements ShouldBroadcast  
{
use InteractsWithSockets, SerializesModels;

public $chatMessage;
public $user;

/**
* Create a new event instance.
*
* @param $chatMessage
* @param $user
*/
public function __construct($chatMessage, $user)
{
$this->chatMessage = $chatMessage;
$this->user = $user;
}

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

With our route file web.php file, we will set a route for JavaScript for making an ajax call with a message.

// Send a message by Javascript.
Route::post('message', function(Request $request) {

$user = Auth::user();

$message = ChatMessage::create([
'user_id' => $user->id,
'message' => $request->input('message')
]);

event(new ChatMessageWasReceived($message, $user));


});

We grab the logged in user right to insert the id and the message in the given chat_messages table and also the fire of the event with the message and the user object.

All this completely covers the backend.

Frontend setup

Laravel 5.4 ships with some of the javascript files which will setup jquery, bootstrap, vue and vue-resource is really handy for getting up and running fast.

Next step will be to import Laravel Echo’s frontend library and then do that by resources/assets/js/bootstrap.js with the some code which is made a comment, uncomment that to see:

import Echo from "laravel-echo"

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

Just remember to add the own pusher key.

The next step will be to go and create a file named chat.js and then put it accordingly into javascript components folder and accordingly add this code.

module.exports = {

data() {
return {
posts: [],
newMsg: '',

}
},


ready() {
Echo.channel('public-test-channel')
.listen('ChatMessageWasReceived', (data) => {

// Push ata to posts list.
this.posts.push({
message: data.chatMessage.message,
username: data.user.name
});
});
},

methods: {

press() {

// Send message to backend.
this.$http.post('/message/', {message: this.newMsg})
.then((response) => {

// Clear input field.
this.newMsg = '';
});
}
}
};

First of all in ready() method, it will listen for channel public-test-channel which is specified in the Event ChatMessageWasRecieved

Next it will listen for any events which come right to Event Class and then accordingly push the received data into posts data array.

The press () method will accordingly send an ajax request right to route file with the message typed by the user in view. And the last we need is to add the component to the app.js file in the following way.

Vue.component('example', require('./components/Example.vue'));  
Vue.component('chat', require('./components/chat'));

Setting up the view file

The last step will be to add an input field for the user to begin to chat. The good place to add that is in the home.blade.php file which ships with Laravel by deflaut. One can then find the file in resources/views/home.blade.php.

<div class="panel-body">  
<chat inline-template>

You are logged in!

<hr>

<h2>Write something to all users</h2>
<input type="text" class="form-control" placeholder="something" required="required" v-model="newMsg" @keyup.enter="press">

<hr>
<h3>Messages</h3>

<ul v-for="post in posts">
<b>@{{ post.username }} says:</b> @{{ post.message }}</li>
</ul>

</chat>
</div><!-- panel-body -->

We add a input fiekd along with the v-model = “newMsg” and a @keyup.enter=”press” for triggering the Vue method when the user press Enter.

In the <url>, one will just loop through the user’s posts.

Wrapping up

So that is the way to create a simple chat app with Laravel 5.3 and Vue. Try opening two browser and see if it is working.

Written by

Webskitters is a premium web development and design company offering expertise services to clients spread across seven countries.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade