Build a live comments feature using Laravel
A basic understanding of Laravel and Vue.js is needed to follow this tutorial.
Live commenting allows users to see new comments from other users without reloading the page. This paves a way to have better collaboration and conversation between friends and collaborators. It brings dynamic feel to the application interface and a better usability.
Today, we will create a live commenting system using Laravel and Pusher. With the release of Echo, Laravel has provided an out of the box solution for implementing realtime data synchronisation using event broadcasting. It is simple and we can get started in a matter of few minutes.
A basic understanding of Laravel and Vue is needed to understand this tutorial.
Setup an app on Pusher
We need to sign up on Pusher and create a new app.
Install Laravel, Pusher SDK and Echo
First, we will grab a fresh copy of Laravel:
laravel new live-commenting-pusher-laravel
This will install the latest version of the Laravel framework and download the necessary dependencies. Next, we will install the Pusher PHP SDK using Composer:
composer require pusher/pusher-php-server
Next, we will install the JavaScript dependencies:
npm install
Now, we need to install two Javascript libraries necessary for realtime event broadcasting: Laravel Echo and Pusher JS
npm install --save laravel-echo pusher-js
We require some form of user authentication mechanism to demonstrate the functionality. Let us use the default authentication scaffolding provided by Laravel:
php artisan make:auth
Configuration
First, we need to set the APP_ID
, APP_KEY
, APP_SECRET
and APP_CLUSTER
in the environment file. We can get these details in our Pusher app dashboard:
# .env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster
Next, we need to create a fresh Echo instance in our applications’s JavaScript. We can do so at the bottom of our resources/assets/js/bootstrap.js
file:
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-app-key',
cluster: 'ap2',
encrypted: true
});
Our application
We will create a live commenting functionality for a video similar to what YouTube does. The core feature is the number of users active on this page and whenever a user comments on the video, it will be automatically broadcasted as a feed of the comments to all the viewers who are viewing this video. We will not cover anything relating to writing CRUD functionality using Laravel. We will concentrate on the code necessary for implementing the live commenting feature. The code is available on a Github repository for cloning and understanding purposes.
Online users
We will now show the number of users who are currently online on the video page. This is a typical feature where we show a message: 2 users watching now. Whenever a new user joins or leaves the page, the count is automatically updated. Let us implement that with Echo and it is super simple. Let us go and fill out our listen
method in the Example
Vue component.
listen() {
Echo.join('video')
.here((users) => {
this.count = users.length;
})
.joining((user) => {
this.count++;
})
.leaving((user) => {
this.count--;
});
}
join
is used when we want to join a presence channel and that is used to tell us who else is on the page. Presence channels are automatically private channels. We do need to authenticate them.
here
gives us a list of users that are also present on the same page.
joining
will be executed whenever a new user joins the channel or page in the above scenario.
leaving
will be executed whenever a user leaves the channel.
Below is the demonstration where the count of users present on the page is updated automatically when a user leaves or joins the page.
Migrations
Next, we need a comments
table where we can store all the comments for the video.
php artisan make:model Comment -m
The comments
table would require the following fields:
- Body of each comment
- A field to link the comment to the user that created it
- A field to link the comment to the video for which it is posted
Below is the migration for our comments
table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->text('body');
$table->integer('video_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
Broadcasting new comments
Whenever a new comment is created, we need to fire an event which will be broadcasted over Pusher to a specific presence channel. For broadcasting an event, it should implement the ShouldBroadcast
interface. Let us first create the NewComment
event:
php artisan make:event NewComment
broadcastOn method
The event should implement a broadcastOn
method. This method should return the presence channel to which the event should be broadcasted.
namespace App\Events;
use App\Comment;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewComment implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
public function broadcastOn()
{
return new PresenceChannel('video');
}
public function broadcastWith()
{
return [
'id' => $this->comment->id,
'body' => $this->comment->body,
'user' => [
'name' => $this->comment->user->name,
'id' => $this->comment->user->id,
],
];
}
}
Next, we need to start our queue to actually listen for jobs and broadcast any events that are recorded. We can use the database queue listener on our local environment:
php artisan queue:listen
Broadcast the event
Whenever a new comment is created, we will broadcast the NewComment
event using the broadcast
helper:
public function store(Video $video)
{
$comment = $video->comments()->create([
'body' => request('body'),
'user_id' => auth()->user()->id,
'video_id' => $video->id
]);
$comment = Comment::where('id', $comment->id)->with('user')->first();
broadcast(new NewComment($comment))->toOthers();
return $comment;
}
Whenever we create a new comment, we push it to the comments
variable so that it is reflected instantly for the user. If we do not use the toOthers
method, then the event would also be broadcasted to the user who has created it. This would create a list of duplicate comments.
toOthers
allows you to exclude the current user from the broadcast’s recipients.
Listening for new comments on the presence channel
Installation and configuration of Laravel Echo is a must before we can start listening to new comments. We have covered the process in detail in the above section of this article. Please go through it if you might have skipped it.
Echo.join('video')
.here((users) => {
this.count = users.length;
})
.joining((user) => {
this.count++;
})
.leaving((user) => {
this.count--;
})
.listen('NewComment', (e) => {
this.comments.unshift(e);
});
Authorization
Every presence channel is a private channel. Laravel Echo will automatically call the specified authentication route. But, we still need to write the authentication logic which will actually authorize the user to listen to a particular channel.
Authorization logic is written in the routes/channels.php
. The authorization logic for our video
channel is:
Broadcast::channel('video', function ($user) {
return [
'id' => $user->id,
'name' => $user->name,
];
});
We are not going to return true
or false
. If the user is authenticated to listen on this presence channel we are going to return an array of data that we want to be returned to that callback in the listen
method.
You can write the authentication logic as required for your application in the above callback and return null if authorization fails.
Vue Component
That’s it! Now, whenever a new comment is created, it will be broadcast and we can listen using our presence channel.
Below is our Example component written using Vue.js
<template>
<div class="container">
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading" id="accordion">
<span class="glyphicon glyphicon-comment"></span> Chat
<div class="btn-group pull-right">
<a type="button" class="btn btn-default btn-xs" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
</div>
<div class="panel-collapse collapse" id="collapseOne">
<div class="panel-body">
<ul class="chat">
<li class="left clearfix" v-for="comment in comments">
<span class="chat-img pull-left">
<img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">{{ comment.user.name }}</strong> <small class="pull-right text-muted">
<span class="glyphicon glyphicon-time"></span>12 mins ago</small>
</div>
<p>
{{ comment.body }}
</p>
</div>
</li>
</ul>
</div>
<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." v-model="body" @keyup.enter="postComment()" />
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" id="btn-chat" @click.prevent="postComment()">
Send</button>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-7">
<iframe width="640" height="280" src="https://www.youtube.com/embed/Xip2TgAEVz4" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<h1>
{{ count }} watching now
</h1>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['user', 'video'],
data() {
return {
viewers: [],
comments: [],
body: 'Your comment',
count: 0
}
},
mounted() {
this.listen();
this.getComments();
},
methods: {
getComments() {
axios.get('/api/videos/'+ this.video.id +'/comments?api_token=' + this.user.api_token, {})
.then((response) => {
this.comments = response.data;
});
},
postComment() {
axios.post('/api/videos/'+ this.video.id +'/comment?api_token=' + this.user.api_token, {
body: this.body
})
.then((response) => {
this.comments.unshift(response.data);
});
},
listen() {
Echo.join('video')
.here((users) => {
this.count = users.length;
})
.joining((user) => {
this.count++;
})
.leaving((user) => {
this.count--;
})
.listen('NewComment', (e) => {
this.comments.unshift(e);
});
}
}
}
</script>
Below is the image demonstrating the workflow of our system:
Conclusion
In this article, we have covered how to create a live commenting system using Laravel and Pusher. We have covered the configuration options necessary to get started, and the example above should help you fill in the gaps and give an overview of some of the other configuration options available to you.
10 March 2017
by Viraj Khatavkar